httpclient4.5.2 Post请求支持http和https
先导入所需的jar包,pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version><!--$NO-MVN-MAN-VER$-->
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version><!--$NO-MVN-MAN-VER$-->
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
写一个工具类 HttpUtil
package cn.nintendoswitch.user.api.boot.common.util; import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClients; public class HttpUtil { public static String doPost(String url, Header[] headers, Map<String, Object> paramMaps) {
String result = null;
HttpPost httpPost = new HttpPost(url);
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
try {
httpPost.setHeaders(headers);
List<NameValuePair> pairList = new ArrayList<>();
for (Map.Entry<String, Object> entry : paramMaps.entrySet()) {
String key = entry.getKey();
String value = (String) entry.getValue();
pairList.add(new BasicNameValuePair(key, value));
}
UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(pairList, "UTF-8");
httpPost.setEntity(urlEntity);
HttpResponse resp = closeableHttpClient.execute(httpPost);
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(resp.getEntity(), "UTF-8").trim();
}
} catch (Exception e) {
throw new RuntimeException("HTTP post failed.", e);
} finally {
httpPost.abort();
try {
closeableHttpClient.close();
} catch (Exception e2) {
throw new RuntimeException("Close CloseableHttpClient failed.", e2);
}
} return result;
} // 使用代理服务器IP 请求出去
public static String doHttpsPost(String url, Header[] headers, Map<String, Object> paramMaps) {
// 设置代理
HttpHost proxy = new HttpHost(代理IP, 端口号, "http");
RequestConfig defaultRequestConfig = RequestConfig.custom().setProxy(proxy).build(); String result = null;
CloseableHttpClient httpClient = null;
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setHeaders(headers);
httpPost.setEntity(httpEntity);
httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
HttpResponse resp = httpClient.execute(httpPost);
result = EntityUtils.toString(resp.getEntity(), "UTF-8").trim();
} catch (Exception e) {
throw new RuntimeException("HTTP Post failed.", e);
} finally {
httpPost.abort();
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException("Close CoseabledHttpClient failed.", e);
}
}
return result;
} }
写个测试调用方法:
package cn.nintendoswitch.user.api.boot.controller; import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.nintendoswitch.user.api.boot.common.util.HttpUtil;
import io.jsonwebtoken.impl.Base64Codec; @Controller
public class IndexController { @RequestMapping("/indexPage")
public void indexPage(HttpServletRequest request, HttpServletResponse response) {
System.out.println("welcome to shanghai.");
} @RequestMapping("/testPostWaveToken")
public void testPostWaveToken(HttpServletRequest request, HttpServletResponse response) {
String url = "https://xxxxxx.com.cn/aaa/bbb/"; String base64Content = "12121212121:aaaaaaaaaaaaa";
String encodeContent = Base64Codec.BASE64.encode(base64Content);
Header[] headers = {new BasicHeader("token", "ABCDEF " + encodeContent),
new BasicHeader("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE)};
Map<String, Object> paramMaps = new HashMap<>();
paramMaps.put("param01", "value01");
String resutlMsg = HttpUtil.doPost(url, headers, paramMaps);
System.out.println("return info is : " + resutlMsg);
}
}
好了,备忘一下,需要的朋友可以转载,但请注明原著来源,谢谢。
httpclient4.5.2 Post请求支持http和https的更多相关文章
- HttpClient4.X发送Get请求的url参数拼接
HttpClient4.X发送Get请求的参数拼接 使用httpClient发送get请求时,请求参数可以以?key=val&key1=val1的拼接到url后面. 但是请求参数较多时,这种方 ...
- Spring Boot Web应用开发 CORS 跨域请求支持:
Spring Boot Web应用开发 CORS 跨域请求支持: 一.Web开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS等等CORS与JSONP相比 1. JSONP只能实现 ...
- nginx将http升级到https并且同时支持http和https两种请求、http自动转向https
1.http升级到https 1.1.检查 Nginx 是否支持 SSL /usr/local/nginx/sbin/nginx -V configure arguments中是否有--with-ht ...
- 【Nginx】将http升级到https并且同时支持http和https两种请求
一.如何将http升级到https 需要满足下面三个: 1.域名 2.nginx 3.SSL证书 一般第三方证书颁发机构下发的证书是收费的,一年好几千. 1) 从腾讯云申请免费的SSL证 ...
- HttpUtil工具类,发送Get/Post请求,支持Http和Https协议
HttpUtil工具类,发送Get/Post请求,支持Http和Https协议 使用用Httpclient封装的HttpUtil工具类,发送Get/Post请求 1. maven引入httpclien ...
- 测试平台系列(92) 让http请求支持文件上传
大家好~我是米洛! 我正在从0到1打造一个开源的接口测试平台, 也在编写一套与之对应的教程,希望大家多多支持. 欢迎关注我的公众号米洛的测开日记,获取最新文章教程! 回顾 上一节呢,我们编写了oss的 ...
- HTTP请求响应过程 与HTTPS区别
原文:HTTP请求响应过程 与HTTPS区别 HTTP协议学习笔记,基础,干货 HTTP协议 HTTP协议主要应用是在服务器和客户端之间,客户端接受超文本. 服务器按照一定规则,发送到客户端(一般是浏 ...
- Https系列之三:让服务器同时支持http、https,基于spring boot
Https系列会在下面几篇文章中分别作介绍: 一:https的简单介绍及SSL证书的生成二:https的SSL证书在服务器端的部署,基于tomcat,spring boot三:让服务器同时支持http ...
- 牛客网Java刷题知识点之UDP协议是否支持HTTP和HTTPS协议?为什么?TCP协议支持吗?
不多说,直接上干货! 福利 => 每天都推送 欢迎大家,关注微信扫码并加入我的4个微信公众号: 大数据躺过的坑 Java从入门到架构师 人工智能躺过的坑 ...
随机推荐
- 011-数据结构-树形结构-B+树[mysql应用]、B*树
一.B+树概述 B+树是B树的变种,有着比B树更高的查询效率. 一棵 B+ 树需要满足以下条件: 节点的子树数和关键字数相同(B 树是关键字数比子树数少一) 节点的关键字表示的是子树中的最大数,在子树 ...
- excel VBA 密码设置问题
Excel中VBA设置密码的步骤如下: 1.右键点击任何工作表,选择VBAProject属性: 2.在新对话框总,选择“保护”选项卡: 3.勾选查看时锁定,输入密码即可.
- CFCA证书工具类
jar:com.cfca.pkibase-1.0.jar import java.io.UnsupportedEncodingException; import java.security.Secur ...
- k8s记录-helm部署(九)
helm 组件配置在 192.168.0.1 192.168.0.2 192.168.0.3 app 用户下操作tar xvf helm-v2.14.3-linux-amd64.tar.gzsudo ...
- 转 perl DBI 总结
https://www.cnblogs.com/homezzm/archive/2011/07/22/2113618.html ##查看已经安装的包 #!/usr/bin/perluse strict ...
- 【剑指offer】面试题 24. 反转链表
面试题 24. 反转链表
- python 能做什么(常用库)
1. 编写脚本,如测试脚本.初始化脚本.运维脚本:pywin32.nose2. 图形界面开发: Tkinter.PyQt . wxPython . PySide .Pillow3. 爬虫: Scrap ...
- TensorFlow学习笔记(1)—— 基本概念与框架
入门框架时的常见问题 学习框架的原因? 方便.易用 学习框架的哪些知识点? 掌握一个项目的基本流程,就知道需要学习哪些知识点了 迅速学习框架的方法 根据项目每块流程的需要针对性的学 可以看官方的入门教 ...
- kubernetes1.16 配置 metrics-server
kubernetes1.16 版本对应最新的metrics-server为v0.3.5. 下载metrics-server配置文件 git clone https://github.com/kuber ...
- [LOJ6432] [PKUSC2018] 真实排名
题目链接 LOJ:https://loj.ac/problem/6432 Solution 假设我们当前要算\(x\)的答案,分两种情况讨论: \(x\)没被翻倍,那么\([a_x/2,a_x]\)这 ...