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、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.2、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.3、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.4、上传文件
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.5、上传文件及发送键值对数据
public static void multi() {
String requestPath = "http://localhost:8080/demo/httptest/multi";
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost post = new HttpPost(requestPath);
FileBody file = new FileBody(new File("d:/a.jpg"));
HttpEntity requestEntity = MultipartEntityBuilder.create()
.addPart("file", file)
.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")))
.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()
.addPart("file", file)
.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")))
.build())
.execute().returnContent().asString(Charset.forName("utf-8"));
System.out.println("multi fluent返回结果:" + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
close(httpClient);
}
}
2.6、完整例子
package com.inspur.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.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);
FileBody file = new FileBody(new File("d:/a.jpg"));
HttpEntity requestEntity = MultipartEntityBuilder.create()
.addPart("file", file)
.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")))
.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()
.addPart("file", file)
.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")))
.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.inspur.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.TrustSelfSignedStrategy;
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.inspur.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"); //不需要客户端证书
requestPath = "https://10.40.x.x:9010/zsywservice";
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())); //需要客户端证书
requestPath = "https://10.40.x.x:9016/zsywservice";
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 TrustSelfSignedStrategy());
}
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();
}
} }
Java调用Http/Https接口(4)--HttpClient调用Http/Https接口的更多相关文章
- java 通过httpclient调用https 的webapi
java如何通过httpclient 调用采用https方式的webapi?如何验证证书.示例:https://devdata.osisoft.com/p...需要通过httpclient调用该接口, ...
- Java调用Http/Https接口(5)--HttpAsyncClient调用Http/Https接口
HttpAsyncClient是HttpClient的异步版本,提供异步调用的api.文中所使用到的软件版本:Java 1.8.0_191.HttpClient 4.1.4. 1.服务端 参见Java ...
- Java之HttpClient调用WebService接口发送短信源码实战
摘要 Java之HttpClient调用WebService接口发送短信源码实战 一:接口文档 二:WSDL 三:HttpClient方法 HttpClient方法一 HttpClient方法二 Ht ...
- httpclient调用https
httpclient调用https报错: Exception in thread "main" java.lang.Exception: sun.security.validato ...
- 【WebApi】通过HttpClient调用Web Api接口
HttpClient是一个封装好的类,它在很多语言中都有被实现,现在HttpClient最新的版本是4.5. 它支持所有的http方法,自动转向,https协议,代理服务器. 一.Api接口参数标准化 ...
- Java WebService接口生成和调用 图文详解>【转】【待调整】
webservice简介: Web Service技术, 能使得运行在不同机器上的不同应用无须借助附加的.专门的第三方软件或硬件, 就可相互交换数据或集成.依据Web Service规范实施的应用之间 ...
- c#代码 天气接口 一分钟搞懂你的博客为什么没人看 看完python这段爬虫代码,java流泪了c#沉默了 图片二进制转换与存入数据库相关 C#7.0--引用返回值和引用局部变量 JS直接调用C#后台方法(ajax调用) Linq To Json SqlServer 递归查询
天气预报的程序.程序并不难. 看到这个需求第一个想法就是只要找到合适天气预报接口一切都是小意思,说干就干,立马跟学生沟通价格. 不过谈报价的过程中,差点没让我一口老血喷键盘上,话说我们程序猿的人 ...
- httpclient调用webservice接口的方法实例
这几天在写webservice接口,其他的调用方式要生成客户端代码,比较麻烦,不够灵活,今天学习了一下httpclient调用ws的方式,感觉很实用,话不多说,上代码 http://testhcm.y ...
- 使用HttpClient调用第三方接口
最近项目中需要调用第三方的Http接口,这里我用到了HttpClient. 首先我们要搞明白第三方接口中需要我们传递哪些参数.数据,搞明白参数以后我们就可以使用HttpClient调用接口了. 1.调 ...
随机推荐
- php – 通过curl从url获取JSON数据
我试图通过curl连接从URL获取JSON数据.当我打开链接时:它显示{“version”:“N / A”,“success”:true,“status”:true}.现在,我希望获得以上内容. 到目 ...
- 【转】Spring Boot @Condition 注解,组合条件你知道吗
原文:https://www.cnblogs.com/FraserYu/p/11280420.html 上一篇文章 你应该知道的 @ConfigurationProperties 注解的使用姿势,这一 ...
- 坐标转换7参数计算工具——arcgis 地理处理工具案例教程
坐标转换7参数计算工具--arcgis 地理处理工具案例教程 商务合作,科技咨询,版权转让:向日葵,135-4855_4328,xiexiaokui#qq.com 不接受个人免费咨询. 提供API,独 ...
- unix_timestamp 时间戳函数用法(hive)
pandas和SQL数据分析实战 https://study.163.com/course/courseMain.htm?courseId=1006383008&share=2&sha ...
- java8学习
1.Function函数 public static void main(String[] args) { TestController t = new TestController(); new T ...
- 平时没有怎么用Excel做 加减乘除 计算,猛地发现,其实Excel 是一个很好的简单计算器
平时没有怎么用Excel做 加减乘除 计算,猛地发现,其实Excel 是一个很好的简单计算器
- js比较时间大于6个月
//mons是比较的月数,如 2019-02-01 14:27:08 - 2019-08-01 14:27:08 function compareTime(mons,stTime,endTime){ ...
- react问题You must install peer dependencies yourself.
npm WARN react-native@0.46.4 requires a peer of react@16.0.0-alpha.12 but none is installed. You mus ...
- 使用CompletableFuture实现业务服务的异步调用实战代码
假如我有一个订单相关的统计接口,需要返回3样数据:今日订单数.今日交易额.总交易额. 一般的我们的做法是串行调用3个函数,把调用返回的结果返回给调用者,这3次调用时串行执行的,如果每个调用耗时1秒的话 ...
- 9个PNG透明图片免费下载网站推荐
9个PNG透明图片免费下载网站推荐 酷站推荐 2017.08.06 13:47 png格式的图片因为去掉了的背景,方便使用在任何颜色的背景,所以对于从事设计师的朋友来说,经常会用到png透明图片.相信 ...