Commons-HttpClient原來是Apache Commons項目下的一個組件,現已被HttpComponents項目下的HttpClient組件所取代;作為調用Http接口的一種選擇,本文介紹下其使用方法。文中所使用到的軟件版本:Java 1.8.0_191、Commons-HttpClient 3.1。
1、服務端
2、調用Http接口
2.1、GET請求
public static void get() { try { String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=" + URLEncoder.encode("李白", "utf-8"); HttpClient httpClient = new HttpClient(); GetMethod get = new GetMethod(requestPath); int status = httpClient.executeMethod(get); if (status == HttpStatus.SC_OK) { System.out.println("GET返回結果:" + new String(get.getResponseBody())); } else { System.out.println("GET返回狀態碼:" + status); } } catch (Exception e) { e.printStackTrace(); } }
2.2、POST請求(發送鍵值對數據)
public static void post() { try { String requestPath = "http://localhost:8080/demo/httptest/getUser"; HttpClient httpClient = new HttpClient(); PostMethod post = new PostMethod(requestPath); post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); String param = "userId=1000&userName=李白"; post.setRequestEntity(new ByteArrayRequestEntity(param.getBytes())); int status = httpClient.executeMethod(post); if (status == HttpStatus.SC_OK) { System.out.println("POST返回結果:" + new String(post.getResponseBody())); } else { System.out.println("POST返回狀態碼:" + status); } } catch (Exception e) { e.printStackTrace(); } }
2.3、POST請求(發送JSON數據)
public static void post2() { try { String requestPath = "http://localhost:8080/demo/httptest/addUser"; HttpClient httpClient = new HttpClient(); PostMethod post = new PostMethod(requestPath); post.addRequestHeader("Content-type", "application/json"); String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}"; post.setRequestEntity(new ByteArrayRequestEntity(param.getBytes())); int status = httpClient.executeMethod(post); if (status == HttpStatus.SC_OK) { System.out.println("POST json返回結果:" + new String(post.getResponseBody())); } else { System.out.println("POST json返回狀態碼:" + status); } } catch (Exception e) { e.printStackTrace(); } }
2.4、上傳文件
public static void upload() { try { String requestPath = "http://localhost:8080/demo/httptest/upload"; HttpClient httpClient = new HttpClient(); PostMethod post = new PostMethod(requestPath); FileInputStream fileInputStream = new FileInputStream("d:/a.jpg"); post.setRequestEntity(new InputStreamRequestEntity(fileInputStream)); int status = httpClient.executeMethod(post); if (status == HttpStatus.SC_OK) { System.out.println("upload返回結果:" + new String(post.getResponseBody())); } else { System.out.println("upload返回狀態碼:" + status); } } catch (Exception e) { e.printStackTrace(); } }
2.5、上傳文件及發送鍵值對數據
public static void multi() { try { String requestPath = "http://localhost:8080/demo/httptest/multi"; HttpClient httpClient = new HttpClient(); PostMethod post = new PostMethod(requestPath); File file = new File("d:/a.jpg"); Part[] parts = {new FilePart("file", file), new StringPart("param1", "參數1", "utf-8"), new StringPart("param2", "參數2", "utf-8")}; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); int status = httpClient.executeMethod(post); if (status == HttpStatus.SC_OK) { System.out.println("multi返回結果:" + new String(post.getResponseBody())); } else { System.out.println("multi返回狀態碼:" + status); } } catch (Exception e) { e.printStackTrace(); } }
2.6、完整例子
package com.inspur.demo.http.client; import java.io.File; import java.io.FileInputStream; import java.net.URLEncoder; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.ByteArrayRequestEntity; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.InputStreamRequestEntity; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.StringPart; /** * * 通過Commons-HttpClient調用Http接口 * */ public class CommonsHttpClientCase { /** * GET請求 */ public static void get() { try { String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=" + URLEncoder.encode("李白", "utf-8"); HttpClient httpClient = new HttpClient(); GetMethod get = new GetMethod(requestPath); int status = httpClient.executeMethod(get); if (status == HttpStatus.SC_OK) { System.out.println("GET返回結果:" + new String(get.getResponseBody())); } else { System.out.println("GET返回狀態碼:" + status); } } catch (Exception e) { e.printStackTrace(); } } /** * POST請求(發送鍵值對數據) */ public static void post() { try { String requestPath = "http://localhost:8080/demo/httptest/getUser"; HttpClient httpClient = new HttpClient(); PostMethod post = new PostMethod(requestPath); post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); String param = "userId=1000&userName=李白"; post.setRequestEntity(new ByteArrayRequestEntity(param.getBytes())); int status = httpClient.executeMethod(post); if (status == HttpStatus.SC_OK) { System.out.println("POST返回結果:" + new String(post.getResponseBody())); } else { System.out.println("POST返回狀態碼:" + status); } } catch (Exception e) { e.printStackTrace(); } } /** * POST請求(發送json數據) */ public static void post2() { try { String requestPath = "http://localhost:8080/demo/httptest/addUser"; HttpClient httpClient = new HttpClient(); PostMethod post = new PostMethod(requestPath); post.addRequestHeader("Content-type", "application/json"); String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}"; post.setRequestEntity(new ByteArrayRequestEntity(param.getBytes())); int status = httpClient.executeMethod(post); if (status == HttpStatus.SC_OK) { System.out.println("POST json返回結果:" + new String(post.getResponseBody())); } else { System.out.println("POST json返回狀態碼:" + status); } } catch (Exception e) { e.printStackTrace(); } } /** * 上傳文件 */ public static void upload() { try { String requestPath = "http://localhost:8080/demo/httptest/upload"; HttpClient httpClient = new HttpClient(); PostMethod post = new PostMethod(requestPath); FileInputStream fileInputStream = new FileInputStream("d:/a.jpg"); post.setRequestEntity(new InputStreamRequestEntity(fileInputStream)); int status = httpClient.executeMethod(post); if (status == HttpStatus.SC_OK) { System.out.println("upload返回結果:" + new String(post.getResponseBody())); } else { System.out.println("upload返回狀態碼:" + status); } } catch (Exception e) { e.printStackTrace(); } } /** * 上傳文件及發送鍵值對數據 */ public static void multi() { try { String requestPath = "http://localhost:8080/demo/httptest/multi"; HttpClient httpClient = new HttpClient(); PostMethod post = new PostMethod(requestPath); File file = new File("d:/a.jpg"); Part[] parts = {new FilePart("file", file), new StringPart("param1", "參數1", "utf-8"), new StringPart("param2", "參數2", "utf-8")}; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); int status = httpClient.executeMethod(post); if (status == HttpStatus.SC_OK) { System.out.println("multi返回結果:" + new String(post.getResponseBody())); } else { System.out.println("multi返回狀態碼:" + status); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { get(); post(); post2(); upload(); multi(); } }
3、調用Https接口
與調用Http接口不一樣的部分主要在設置ssl部分,設置方法是自己實現ProtocolSocketFactory接口;其ssl的設置與HttpsURLConnection很相似(參見Java調用Http/Https接口(2)--HttpURLConnection/HttpsURLConnection調用Http/Https接口);下面用GET請求來演示ssl的設置,其他調用方式類似。
package com.inspur.demo.http.client; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.UnknownHostException; import java.security.KeyStore; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import com.inspur.demo.common.util.FileUtil; /** * * 通過Commons-HttpClient調用Https接口 * */ public class CommonsHttpClientHttpsCase { public static void main(String[] args) { try { HttpClient httpClient = new HttpClient(); /* * 請求有權威證書的地址 */ String requestPath = "https://www.baidu.com/"; GetMethod get = new GetMethod(requestPath); httpClient.executeMethod(get); System.out.println("GET1返回結果:" + new String(get.getResponseBody())); /* * 請求自定義證書的地址 */ //獲取信任證書庫 KeyStore trustStore = getkeyStore("jks", "d:/temp/cacerts", "123456"); //不需要客戶端證書 requestPath = "https://10.40.103.48:9010/zsywservice"; Protocol.registerProtocol("https", new Protocol("https", new HttpsProtocolSocketFactory(trustStore), 443)); get = new GetMethod(requestPath); httpClient.executeMethod(get); System.out.println("GET2返回結果:" + new String(get.getResponseBody())); //需要客戶端證書 requestPath = "https://10.40.103.48:9016/zsywservice"; KeyStore keyStore = getkeyStore("pkcs12", "d:/client.p12", "123456"); Protocol.registerProtocol("https", new Protocol("https", new HttpsProtocolSocketFactory(keyStore, "123456", trustStore), 443)); get = new GetMethod(requestPath); httpClient.executeMethod(get); System.out.println("GET3返回結果:" + new String(get.getResponseBody())); } catch (Exception e) { e.printStackTrace(); } } /** * 獲取證書 * @return */ private static KeyStore getkeyStore(String type, String filePath, String password) { KeyStore keySotre = null; FileInputStream in = null; try { keySotre = KeyStore.getInstance(type); in = new FileInputStream(new File(filePath)); keySotre.load(in, password.toCharArray()); } catch (Exception e) { e.printStackTrace(); } finally { FileUtil.close(in); } return keySotre; } } final class HttpsProtocolSocketFactory implements ProtocolSocketFactory { private KeyStore keyStore; private String keyStorePassword; private KeyStore trustStore; private SSLSocketFactory sslSocketFactory = null; public HttpsProtocolSocketFactory(KeyStore keyStore, String keyStorePassword, KeyStore trustStore) { this.keyStore = keyStore; this.keyStorePassword = keyStorePassword; this.trustStore = trustStore; } public HttpsProtocolSocketFactory(KeyStore trustStore) { this.trustStore = trustStore; } private SSLSocketFactory getSSLSocketFactory() { if (sslSocketFactory != null) { return sslSocketFactory; } try { KeyManager[] keyManagers = null; TrustManager[] trustManagers = null; if (keyStore != null) { KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); keyManagerFactory.init(keyStore, keyStorePassword.toCharArray()); keyManagers = keyManagerFactory.getKeyManagers(); } if (trustStore != null) { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509"); trustManagerFactory.init(trustStore); trustManagers = trustManagerFactory.getTrustManagers(); } else { trustManagers = new TrustManager[] { new DefaultTrustManager() }; } SSLContext context = SSLContext.getInstance("TLSv1.2"); context.init(keyManagers, trustManagers, null); sslSocketFactory = context.getSocketFactory(); return sslSocketFactory; } catch (Exception e) { e.printStackTrace(); } return null; } @Override public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException, UnknownHostException { return getSSLSocketFactory().createSocket(host, port, localAddress, localPort); } @Override public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); if (timeout == 0) { return getSSLSocketFactory().createSocket(host, port, localAddress, localPort); } else { Socket socket = getSSLSocketFactory().createSocket(); SocketAddress localAddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteAddr = new InetSocketAddress(host, port); socket.bind(localAddr); socket.connect(remoteAddr, timeout); return socket; } } @Override public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return getSSLSocketFactory().createSocket(host, port); } } final class DefaultTrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }
