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从入门到架构师 人工智能躺过的坑 ...
随机推荐
- 运维笔记--linux环境提示python: command not found
场景描述: 新部署的容器环境,终端执行python命令,提示没有该命令. 从报错异常可以看出,可能是python环境未安装. 分析思路: 检查python路径: 方式一:type -a python ...
- shell中跳出循环语句break和continue
在使用while或for循环语句过程中,也许碰到某个特殊条件,我们需要跳过当次循环或整个循环,这是就需要借助break和continue. break表示跳出本层循环,break n表示跳出循环的层数 ...
- JS字符串数字前面加加号会变成数字类型
JS中一个字符串中只有数字,如果该字符串前面加了个加号,这个数值就变成了number类型.如本文测试中,用lodop打印二维码,最后一个参数是一个字符串,在前面加了加号和不在前面加加号,通过控制台输出 ...
- [LeetCode] 313. Super Ugly Number 超级丑陋数
Write a program to find the nth super ugly number. Super ugly numbers are positive numbers whose all ...
- 问题二:appium 搞定权限弹框的一个小办法
public void permission() { for (int i=0; i <= 10; i++) { if (getPageSource().contains("允许&qu ...
- Lambda的延迟执行
在兼顾面向对象特性的基础上,Java语言通过Lambda表达式与方法引用等,为开发者打开了函数式编程的大门. 下面我们做一个初探. Lambda的延迟执行 有些场景的代码执行后,结果不一定会被使用,从 ...
- 10 Servlet+Http+Request对象
1.Servlet的体系结构 Servlet -- 接口----->GenericServlet -- 抽象类------->HttpServlet -- 抽象类 (1)GenericSe ...
- Qt 自定义QTabWidget
思路: QTabWidget的特点:点击不同的选项卡显示不同的窗口.可以将QTabWidget分成两部分: (1).选项卡:点击时要知道点击的是哪个选项.则需要将选项卡和窗口的信息存起来,点击时去这个 ...
- Zabbix案例实践|Zabbix屏蔽告警
近期项目中,客户要求在凌晨00:00到02:00的CPU屏蔽虚拟化监控上ESXI的红色告警,红色告警是由于某台vmCPU利用率过高而产生的.做法如下:1. 找到红色告警的触发器,通过触发器找到监控项, ...
- Pandas的基础操作(一)——矩阵表的创建及其属性
Pandas的基础操作(一)——矩阵表的创建及其属性 (注:记得在文件开头导入import numpy as np以及import pandas as pd) import pandas as pd ...