HttpClient 4.5.3 get和post请求
HttpCilent 4.5.3 get 请求 post 请求,https post请求,不用参数类型的post请求
GET请求
CloseableHttpClient httpCilent = HttpClients.createDefault();//Creates CloseableHttpClient instance with default configuration.
HttpGet httpGet = new HttpGet("http://www.baidu.com");
try {
httpCilent.execute(httpGet);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpCilent.close();//释放资源
} catch (IOException e) {
e.printStackTrace();
}
}
GET 设置 超时时间
CloseableHttpClient httpCilent2 = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) //设置连接超时时间
.setConnectionRequestTimeout(5000) // 设置请求超时时间
.setSocketTimeout(5000)
.setRedirectsEnabled(true)//默认允许自动重定向
.build();
HttpGet httpGet2 = new HttpGet("http://www.baidu.com");
httpGet2.setConfig(requestConfig);
String srtResult = "";
try {
HttpResponse httpResponse = httpCilent2.execute(httpGet2);
if(httpResponse.getStatusLine().getStatusCode() == 200){
srtResult = EntityUtils.toString(httpResponse.getEntity());//获得返回的结果
System.out.println(srtResult);
}else if(httpResponse.getStatusLine().getStatusCode() == 400){
//..........
}else if(httpResponse.getStatusLine().getStatusCode() == 500){
//.............
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpCilent2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
POST请求
//获取可关闭的 httpCilent
CloseableHttpClient httpClient = HttpClients.createDefault();
//配置超时时间
RequestConfig requestConfig = RequestConfig.custom().
setConnectTimeout(1000).setConnectionRequestTimeout(1000)
.setSocketTimeout(1000).setRedirectsEnabled(true).build(); HttpPost httpPost = new HttpPost("http://consentprt.dtac.co.th/webaoc/123SubscriberProcess");
//设置超时时间
httpPost.setConfig(requestConfig);
//装配post请求参数
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("age", "20")); //请求参数
list.add(new BasicNameValuePair("name", "zhangsan")); //请求参数
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8");
//设置post求情参数
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
String strResult = "";
if(httpResponse != null){
System.out.println(httpResponse.getStatusLine().getStatusCode());
if (httpResponse.getStatusLine().getStatusCode() == 200) {
strResult = EntityUtils.toString(httpResponse.getEntity());
} else if (httpResponse.getStatusLine().getStatusCode() == 400) {
strResult = "Error Response: " + response.getStatusLine().toString();
} else if (httpResponse.getStatusLine().getStatusCode() == 500) {
strResult = "Error Response: " + response.getStatusLine().toString();
} else {
strResult = "Error Response: " + response.getStatusLine().toString();
}
}else{ }
System.out.println(strResult);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(httpClient != null){
httpClient.close(); //释放资源
}
} catch (IOException e) {
e.printStackTrace();
}
}
Post 请求
public static String doPost(String url, Map<String, Object> paramsMap){
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().
setConnectTimeout(180 * 1000).setConnectionRequestTimeout(180 * 1000)
.setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
httpPost.setConfig(requestConfig);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (String key : paramsMap.keySet()) {
nvps.add(new BasicNameValuePair(key, String.valueOf(paramsMap.get(key))));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
logger.info("httpPost ===**********===>>> " + EntityUtils.toString(httpPost.getEntity()));
HttpResponse response = httpClient.execute(httpPost);
String strResult = "";
if (response.getStatusLine().getStatusCode() == 200) {
strResult = EntityUtils.toString(response.getEntity());
return strResult;
} else {
return "Error Response: " + response.getStatusLine().toString();
}
} catch (Exception e) {
e.printStackTrace();
return "post failure :caused by-->" + e.getMessage().toString();
}finally {
if(null != httpClient){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
POST 请求,参数是json字符串
public static String doPostForJson(String url, String jsonParams){
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().
setConnectTimeout(180 * 1000).setConnectionRequestTimeout(180 * 1000)
.setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
httpPost.setConfig(requestConfig);
httpPost.setHeader("Content-Type","application/json"); //
try {
httpPost.setEntity(new StringEntity(jsonParams,ContentType.create("application/json", "utf-8")));
System.out.println("request parameters" + EntityUtils.toString(httpPost.getEntity()));
HttpResponse response = httpClient.execute(httpPost);
System.out.println(" code:"+response.getStatusLine().getStatusCode());
System.out.println("doPostForInfobipUnsub response"+response.getStatusLine().toString());
return String.valueOf(response.getStatusLine().getStatusCode());
} catch (Exception e) {
e.printStackTrace();
return "post failure :caused by-->" + e.getMessage().toString();
}finally {
if(null != httpClient){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Post 请求上传文件,模拟表单提交文件
依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.4</version>
</dependency>
public static String doPost() {
final String url = "http://10.12.1.104:8080/hello";//
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
try {
File imageFile = new File("D:\\captcha.jpg");
String fileName = imageFile.getName();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// file,类似表单中的name的值,后台通过这个名字取文件
builder.addBinaryBody("file", new FileInputStream(imageFile), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);// 执行提交
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
后台接收文件
@PostMapping("/hello")
@ResponseBody
public Map<String, String> a(MultipartHttpServletRequest multipartRequest) throws IOException {
String filePath = System.getProperties().getProperty("user.home") + "/upload_y"; //获取要保存的路径
MultipartFile file = multipartRequest.getFiles("file").get(0);
String originalFilename = file.getOriginalFilename();
//文件路径
String myfilePath = filePath + File.separator + originalFilename + UUID.randomUUID();
file.transferTo(new File(myfilePath));
return null;
}
https post
直接可以用
public static String postByHttps(String url, Map<String, Object> paramsMap) throws Exception{
X509TrustManager tm = new 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;
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
// 初始化SSL上下文
sslContext.init(null, new TrustManager[] { tm }, null);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).setMaxConnTotal(50)
.setMaxConnPerRoute(50).setDefaultRequestConfig(RequestConfig.custom()
.setConnectionRequestTimeout(60000).setConnectTimeout(60000).setSocketTimeout(60000).build())
.build();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (String key : paramsMap.keySet()) {
nvps.add(new BasicNameValuePair(key, String.valueOf(paramsMap.get(key))));
}
try {
httppost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
logger.info("httpsPost ===**********===>>> " + EntityUtils.toString(httppost.getEntity()));
HttpResponse response = httpclient.execute(httppost);
String strResult = "";
if (response.getStatusLine().getStatusCode() == 200) {
strResult = EntityUtils.toString(response.getEntity());
return strResult;
} else {
logger.info("Error Response:" + response.getStatusLine().toString());
return "Error Response: " + response.getStatusLine().toString();
}
} catch (Exception e) {
e.printStackTrace();
return "post failure :caused by-->" + e.getMessage().toString();
}finally {
if(null != httpclient){
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我在腾讯微视玩短视频 搜索用户 “lei9527”
域名购买.com 后缀好域名
https://mi.aliyun.com/shop/38040
HttpClient 4.5.3 get和post请求的更多相关文章
- 如何使用HttpClient来发送带客户端证书的请求,以及如何忽略掉对服务器端证书的校验
最近要做客户端和服务器端的双向认证,在客户端向服务器端发送带证书的请求这里有一点问题,网上的例子大多都不太好使,于是找了github上httpclient源代码中的例子改造了一下,终于弄明白了 git ...
- httpclient开启代理,获取java中请求的url
背景:在httpclent做post或者get请求时,请求返回的数据总是和预想的不一致,但是有不知道怎么排查问题,经同事说httpclient可以设置代理,就可以获取请求前数据的一些问题,帮助我排查问 ...
- httpclient连接池在ES Restful API请求中的应用
package com.wm.utils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http ...
- 在ASP.NET Core中用HttpClient(三)——发送HTTP PATCH请求
在前面的两篇文章中,我们讨论了很多关于使用HttpClient进行CRUD操作的基础知识.如果你已经读过它们,你就知道如何使用HttpClient从API中获取数据,并使用HttpClient发送PO ...
- HttpClient与APS.NET Web API:请求内容的压缩与解压
首先说明一下,这里的压缩与解压不是通常所说的http compression——那是响应内容在服务端压缩.在客户端解压,而这里是请求内容在客户端压缩.在服务端解压. 对于响应内容的压缩,一般Web服务 ...
- Android入门:用HttpClient模拟HTTP的GET和POST请求
一.HttpClient介绍 HttpClient是用来模拟HTTP请求的,其实实质就是把HTTP请求模拟后发给Web服务器: Android已经集成了HttpClient,因此可以直接使用: ...
- java使用httpclient封装post请求和get的请求
在我们程序员生涯中,经常要复用代码,所以我们应该养成时常整理代码的好习惯,以下是我之前封装的httpclient的post和get请求所用的代码: package com.marco.common; ...
- 使用httpClient连接池处理get或post请求
以前有一个自己写的: http://www.cnblogs.com/wenbronk/p/6482706.html 后来发现一个前辈写的更好的, 再此感谢一下, 确实比我写的那个好用些 1, 创建一个 ...
- 用HttpClient模拟HTTP的GET和POST请求(转)
本文转自:http://blog.csdn.net/xiazdong/article/details/7724349 一.HttpClient介绍 HttpClient是用来模拟HTTP请求的,其 ...
随机推荐
- 转移wordpress到另一台主机
做项目的代码是两个人,我想把另一个小伙伴做的转移到自己的linux系统上(主要是linux下一片空白,从头做太浪费时间了) 这个过程其实也可以用来类比从本地到服务器的过程(可能略有不同,真上线的时候会 ...
- PostgreSQL远程代码执行漏洞(CVE-2018-1058)学习笔记
零.参考文献和绪论: 1.先知社区chybeta大神的--PostgreSQL 远程代码执行漏洞分析及利用—[CVE-2018-1058]--一文 2.博客园hunchill的--Mac 下 Post ...
- PHP一句话木马小总结与SQL语句写一句话木马
一.基础类的一句话--功能仅限于验证漏洞了,实际中太容易被查出出来: <?php @eval($_GET["code"])?> <?php @system($_P ...
- 分布式数据库主键id生成策略
分布式数据库部署主要分为两种,一种是读写分离.这个需要弄主从数据库.主要是写的时候写主数据库,读的时候读从数据库.分散读取压力,对于读多写少的系统有利于 提高其性能.还有一种是分布式存储,这种主要是将 ...
- 160225、解决纯js文件国际化的问题
1.js中国际化 function test(){ alert("<s:text name='jsp.loading'/>"); } 2.最近在做strut ...
- Yii2中省市三级联动(栏目联动)
先从表的设计开始: 表的结构: CREATE TABLE `global_region` ( `region_id` smallint(5) unsigned NOT NULL AUTO_INCREM ...
- Oracle之使用rman进行异机恢复测试记录
本次测试目的是从生产数据库导出rman备份然后在测试数据库恢复 1,拷贝备份至相应目录 2,进入rman rman target \ 3,关闭数据库 shutdown 4,以nomount模式启动数据 ...
- 在唯一密钥属性“fileExtension”设置为“.log”时,无法添加类型为“mimeMap”的重复集合项
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAkoAAAFfCAIAAAA+snR7AAAgAElEQVR4nOzdZ1xT18PAcf+1VpZaW6
- 第二次去苹果店维修MacBook
今天上午,在使用外接鼠标的情况下,屏幕上鼠标指针乱窜.乱点.不受控制的故障再次出现,这次拍下了视频. 再次去苹果网站预约Genius Bar(天才吧),中午的时候去了苹果店.这次没有像上次那样检查身份 ...
- flask源码剖析--请求流程
想了解这篇里面的内容,请先去了解我另外一篇博客Flask上下文 在了解flask之前,我们需要了解两个小知识点 偏函数 import functools def func(a1,a2): print( ...