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从入门到架构师 人工智能躺过的坑 ...
随机推荐
- 企业微信域名IP列表
https://res.mail.qq.com/zh_CN/wework_ip/latest.html?st=C98F886B96A94AD2207D9F0B2970B93DFD5A76DF94CED ...
- MongoDB学习(附录一) 安装mongodb3.6时碰到的问题
1.Installing MongoDB Compass...(this may take a few minutes)这一步,会停留很长时间,点击取消可能也取消不了. 安装mongdodb ,进度卡 ...
- 在使用redis做缓存后,mybatis的延迟加载失效
原来使用的是EHcache,mybatis延迟加载没有问题,改成redis后,延迟加载获得数据时就会发生错误. 报:Cannot get Configuration as configuration ...
- spring的面试
IOC IOC(Inversion Of Controll,控制反转)是一种设计思想,将原本在程序中手动创建对象的控制权,交由给Spring框架来管理.IOC容器是Spring用来实现IOC的载体,I ...
- AR*更新客户地址联系人
CREATE OR REPLACE PACKAGE BODY cux_ar_party_location_pkg IS g_pkg_name CONSTANT VARCHAR2() := 'CUX_A ...
- java 多个数 组合成不同的组
public static Stack<Integer> stack = new Stack<Integer>(); private static List<String ...
- C程序设计语言练习 第二章
2.3 常量 strlen函数:返回s的长度 int strlenn(char s[]) { int i=0; while(s[i] != '\0') ++i; return i; } 2.7 类型转 ...
- PAT(B) 1065 单身狗(Java:17分,C:25分)
题目链接:1065 单身狗 (25 point(s)) 题目描述 "单身狗"是中文对于单身人士的一种爱称.本题请你从上万人的大型派对中找出落单的客人,以便给予特殊关爱. 输入格式 ...
- 【Linux】Linux目录结构及详细介绍
00. 目录 01. 常用目录介绍 /:根目录,位于Linux文件系统目录结构的顶层,一般根目录下只存放目录,不要存放文件,/etc./bin./dev./lib./sbin应该和根目录放置在一个分区 ...
- 【LEETCODE】50、数组分类,简单级别,题目:888,1013,896,485,448,697
package y2019.Algorithm.array; import java.util.HashSet; import java.util.Set; /** * @ProjectName: c ...