Java调用Http/Https接口(4)--HttpClient调用Http/Https接口
HttpClient是Apache HttpComponents项目下的一个组件,是Commons-HttpClient的升级版,两者api调用写法也很类似。文中所使用到的软件版本:Java 1.8.0_191、HttpClient 4.5.10。
1、服务端
2、调用Http接口
2.1、引入依赖
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.13</version> </dependency>
2.2、GET请求
public static void get() { String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李白"; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpGet get = new HttpGet(requestPath); CloseableHttpResponse response = httpClient.execute(get); System.out.println("GET返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("GET返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Get(requestPath).execute().returnContent().asString(Charset.forName("utf-8")); System.out.println("GET fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } finally { close(httpClient); } }
2.3、POST请求(发送键值对数据)
public static void post() { String requestPath = "http://localhost:8080/demo/httptest/getUser"; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost post = new HttpPost(requestPath); List<NameValuePair> list = new ArrayList<NameValuePair>(); list.add(new BasicNameValuePair("userId", "1000")); list.add(new BasicNameValuePair("userName", "李白")); post.setEntity(new UrlEncodedFormEntity(list, "utf-8")); CloseableHttpResponse response = httpClient.execute(post); System.out.println("POST返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("POST返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Post(requestPath) .bodyForm(Form.form().add("userId", "1000").add("userName", "李白").build(), Charset.forName("utf-8")) .execute().returnContent().asString(Charset.forName("utf-8")); System.out.println("POST fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } finally { close(httpClient); } }
2.4、POST请求(发送JSON数据)
public static void post2() { String requestPath = "http://localhost:8080/demo/httptest/addUser"; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost post = new HttpPost(requestPath); post.setHeader("Content-type", "application/json"); String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}"; post.setEntity(new StringEntity(param, "utf-8")); CloseableHttpResponse response = httpClient.execute(post); System.out.println("POST json返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("POST josn返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Post(requestPath) .addHeader("Content-type", "application/json") .bodyString(param, ContentType.APPLICATION_JSON) .execute().returnContent().asString(Charset.forName("utf-8")); System.out.println("POST json fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } finally { close(httpClient); } }
2.5、上传文件
public static void upload() { String requestPath = "http://localhost:8080/demo/httptest/upload"; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost post = new HttpPost(requestPath); FileInputStream fileInputStream = new FileInputStream("d:/a.jpg"); post.setEntity(new InputStreamEntity(fileInputStream)); CloseableHttpResponse response = httpClient.execute(post); System.out.println("upload返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("upload返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Post(requestPath) .bodyStream(new FileInputStream("d:/a.jpg")) .execute().returnContent().asString(Charset.forName("utf-8")); System.out.println("upload fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } finally { close(httpClient); } }
2.6、上传文件及发送键值对数据
public static void multi() { String requestPath = "http://localhost:8080/demo/httptest/multi"; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost post = new HttpPost(requestPath); HttpEntity requestEntity = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.RFC6532) .addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addBinaryBody("files", new File("d:/tmp/测试.xlsx")) .addBinaryBody("files", new File("d:/tmp/测试2.xlsx"), ContentType.DEFAULT_BINARY, "测试2(修改后).xlsx") .addBinaryBody("files", new FileInputStream("d:/tmp/测试3.docx"), ContentType.DEFAULT_BINARY, "测试3(修改后).docx") .addBinaryBody("files", "测试内容".getBytes(), ContentType.DEFAULT_BINARY, "测试.txt") .build(); post.setEntity(requestEntity); CloseableHttpResponse response = httpClient.execute(post); System.out.println("multi返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("multi返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Post(requestPath) .body(MultipartEntityBuilder.create() .setMode(HttpMultipartMode.RFC6532) .addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addBinaryBody("files", new File("d:/tmp/测试.xlsx")) .addBinaryBody("files", new File("d:/tmp/测试2.xlsx"), ContentType.DEFAULT_BINARY, "测试2(修改后).xlsx") .addBinaryBody("files", new FileInputStream("d:/tmp/测试3.docx"), ContentType.DEFAULT_BINARY, "测试3(修改后).docx") .addBinaryBody("files", "测试内容".getBytes(), ContentType.DEFAULT_BINARY, "测试.txt") .build()) .execute().returnContent().asString(Charset.forName("utf-8")); System.out.println("multi fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } finally { close(httpClient); } }
2.7、完整例子
package com.abc.demo.http.client; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.fluent.Form; import org.apache.http.client.fluent.Request; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; /** * 通过HttpClient调用Http接口 */ public class HttpClientCase { /** * GET请求 */ public static void get() { String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李白"; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpGet get = new HttpGet(requestPath); CloseableHttpResponse response = httpClient.execute(get); System.out.println("GET返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("GET返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Get(requestPath).execute().returnContent().asString(Charset.forName("utf-8")); System.out.println("GET fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } finally { close(httpClient); } } /** * POST请求(发送键值对数据) */ public static void post() { String requestPath = "http://localhost:8080/demo/httptest/getUser"; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost post = new HttpPost(requestPath); List<NameValuePair> list = new ArrayList<NameValuePair>(); list.add(new BasicNameValuePair("userId", "1000")); list.add(new BasicNameValuePair("userName", "李白")); post.setEntity(new UrlEncodedFormEntity(list, "utf-8")); CloseableHttpResponse response = httpClient.execute(post); System.out.println("POST返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("POST返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Post(requestPath) .bodyForm(Form.form().add("userId", "1000").add("userName", "李白").build(), Charset.forName("utf-8")) .execute().returnContent().asString(Charset.forName("utf-8")); System.out.println("POST fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } finally { close(httpClient); } } /** * POST请求(发送json数据) */ public static void post2() { String requestPath = "http://localhost:8080/demo/httptest/addUser"; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost post = new HttpPost(requestPath); post.setHeader("Content-type", "application/json"); String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}"; post.setEntity(new StringEntity(param, "utf-8")); CloseableHttpResponse response = httpClient.execute(post); System.out.println("POST json返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("POST josn返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Post(requestPath) .addHeader("Content-type", "application/json") .bodyString(param, ContentType.APPLICATION_JSON) .execute().returnContent().asString(Charset.forName("utf-8")); System.out.println("POST json fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } finally { close(httpClient); } } /** * 上传文件 */ public static void upload() { String requestPath = "http://localhost:8080/demo/httptest/upload"; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost post = new HttpPost(requestPath); FileInputStream fileInputStream = new FileInputStream("d:/a.jpg"); post.setEntity(new InputStreamEntity(fileInputStream)); CloseableHttpResponse response = httpClient.execute(post); System.out.println("upload返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("upload返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Post(requestPath) .bodyStream(new FileInputStream("d:/a.jpg")) .execute().returnContent().asString(Charset.forName("utf-8")); System.out.println("upload fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } finally { close(httpClient); } } /** * 上传文件及发送键值对数据 */ public static void multi() { String requestPath = "http://localhost:8080/demo/httptest/multi"; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost post = new HttpPost(requestPath); HttpEntity requestEntity = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.RFC6532) .addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addBinaryBody("files", new File("d:/tmp/测试.xlsx")) .addBinaryBody("files", new File("d:/tmp/测试2.xlsx"), ContentType.DEFAULT_BINARY, "测试2(修改后).xlsx") .addBinaryBody("files", new FileInputStream("d:/tmp/测试3.docx"), ContentType.DEFAULT_BINARY, "测试3(修改后).docx") .addBinaryBody("files", "测试内容".getBytes(), ContentType.DEFAULT_BINARY, "测试.txt") .build(); post.setEntity(requestEntity); CloseableHttpResponse response = httpClient.execute(post); System.out.println("multi返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("multi返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Post(requestPath) .body(MultipartEntityBuilder.create() .setMode(HttpMultipartMode.RFC6532) .addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addBinaryBody("files", new File("d:/tmp/测试.xlsx")) .addBinaryBody("files", new File("d:/tmp/测试2.xlsx"), ContentType.DEFAULT_BINARY, "测试2(修改后).xlsx") .addBinaryBody("files", new FileInputStream("d:/tmp/测试3.docx"), ContentType.DEFAULT_BINARY, "测试3(修改后).docx") .addBinaryBody("files", "测试内容".getBytes(), ContentType.DEFAULT_BINARY, "测试.txt") .build()) .execute().returnContent().asString(Charset.forName("utf-8")); System.out.println("multi fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } finally { close(httpClient); } } private static void close(CloseableHttpClient httpClient) { try { if (httpClient != null) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { get(); post(); post2(); upload(); multi(); } }
3、调用Https接口
与调用Http接口不一样的部分主要在设置ssl部分,其ssl的设置与HttpsURLConnection很相似(参见Java调用Http/Https接口(2)--HttpURLConnection/HttpsURLConnection调用Http/Https接口);下面用GET请求来演示ssl的设置,其他调用方式类似。
package com.abc.demo.http.client; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.KeyStore; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustAllStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.EntityUtils; import com.abc.demo.common.util.FileUtil; /** * 通过HttpClient调用Https接口 */ public class HttpClientHttpsCase { public static void main(String[] args) { CloseableHttpClient httpClient = null; CloseableHttpClient httpClient2 = null; CloseableHttpClient httpClient3 = null; try { /* * 请求有权威证书的地址 */ String requestPath = "https://www.baidu.com/"; httpClient = HttpClients.createDefault(); HttpGet get = new HttpGet(requestPath); CloseableHttpResponse response = httpClient.execute(get); System.out.println("GET1返回结果:" + EntityUtils.toString(response.getEntity(), "utf-8")); /* * 请求自定义证书的地址 */ //获取信任证书库 KeyStore trustStore = getkeyStore("jks", "d:/temp/cacerts", "123456"); //不需要客户端证书,客户端证书可以是用 keytool 生成的 pks12 格式密钥库,也可以是用 OpenSSL 生成的 pkcs12 格式证书。 requestPath = "https://10.49.196.10:9010/myservice"; SSLConnectionSocketFactory factory = getSSLConnectionSocketFactory(trustStore); httpClient2 = HttpClients.custom().setSSLSocketFactory(factory).build(); get = new HttpGet(requestPath); response = httpClient2.execute(get); System.out.println("GET2返回结果:" + EntityUtils.toString(response.getEntity())); //需要客户端证书,客户端证书可以是用 keytool 生成的 pks12 格式密钥库,也可以是用 OpenSSL 生成的 pkcs12 格式证书。 requestPath = "https://10.49.196.10:9016/myservice"; KeyStore keyStore = getkeyStore("pkcs12", "d:/client.p12", "123456"); factory = getSSLConnectionSocketFactory(keyStore, "123456", trustStore); httpClient3 = HttpClients.custom().setSSLSocketFactory(factory).build(); get = new HttpGet(requestPath); response = httpClient3.execute(get); System.out.println("GET3返回结果:" + EntityUtils.toString(response.getEntity())); } catch (Exception e) { e.printStackTrace(); } finally { close(httpClient); close(httpClient2); close(httpClient3); } } public static SSLConnectionSocketFactory getSSLConnectionSocketFactory(KeyStore trustStore) throws Exception { return getSSLConnectionSocketFactory(null, null, trustStore); } public static SSLConnectionSocketFactory getSSLConnectionSocketFactory(KeyStore keyStore, String keyStorePassword, KeyStore trustStore) throws Exception { SSLContextBuilder bulider = SSLContexts.custom(); if (keyStore != null) { bulider.loadKeyMaterial(keyStore, keyStorePassword.toCharArray()); } if (trustStore != null) { bulider.loadTrustMaterial(trustStore, null); } else { bulider.loadTrustMaterial(new TrustAllStrategy()); } SSLContext sslContext = bulider.build(); // 验证URL的主机名和服务器的标识主机名是否匹配 HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { // if ("xxx".equals(hostname)) { // return true; // } else { // return false; // } return true; } }; SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1", "TLSv1.2" }, null, hostnameVerifier); return factory; } public static SSLConnectionSocketFactory getSSLConnectionSocketFactory() throws Exception { return getSSLConnectionSocketFactory(null, null, null); } 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; } private static void close(CloseableHttpClient httpClient) { try { if (httpClient != null) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } }