先导入所需的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的更多相关文章

  1. HttpClient4.X发送Get请求的url参数拼接

    HttpClient4.X发送Get请求的参数拼接 使用httpClient发送get请求时,请求参数可以以?key=val&key1=val1的拼接到url后面. 但是请求参数较多时,这种方 ...

  2. Spring Boot Web应用开发 CORS 跨域请求支持:

    Spring Boot Web应用开发 CORS 跨域请求支持: 一.Web开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS等等CORS与JSONP相比 1. JSONP只能实现 ...

  3. nginx将http升级到https并且同时支持http和https两种请求、http自动转向https

    1.http升级到https 1.1.检查 Nginx 是否支持 SSL /usr/local/nginx/sbin/nginx -V configure arguments中是否有--with-ht ...

  4. 【Nginx】将http升级到https并且同时支持http和https两种请求

    一.如何将http升级到https 需要满足下面三个: 1.域名 2.nginx 3.SSL证书     一般第三方证书颁发机构下发的证书是收费的,一年好几千.    1) 从腾讯云申请免费的SSL证 ...

  5. HttpUtil工具类,发送Get/Post请求,支持Http和Https协议

    HttpUtil工具类,发送Get/Post请求,支持Http和Https协议 使用用Httpclient封装的HttpUtil工具类,发送Get/Post请求 1. maven引入httpclien ...

  6. 测试平台系列(92) 让http请求支持文件上传

    大家好~我是米洛! 我正在从0到1打造一个开源的接口测试平台, 也在编写一套与之对应的教程,希望大家多多支持. 欢迎关注我的公众号米洛的测开日记,获取最新文章教程! 回顾 上一节呢,我们编写了oss的 ...

  7. HTTP请求响应过程 与HTTPS区别

    原文:HTTP请求响应过程 与HTTPS区别 HTTP协议学习笔记,基础,干货 HTTP协议 HTTP协议主要应用是在服务器和客户端之间,客户端接受超文本. 服务器按照一定规则,发送到客户端(一般是浏 ...

  8. Https系列之三:让服务器同时支持http、https,基于spring boot

    Https系列会在下面几篇文章中分别作介绍: 一:https的简单介绍及SSL证书的生成二:https的SSL证书在服务器端的部署,基于tomcat,spring boot三:让服务器同时支持http ...

  9. 牛客网Java刷题知识点之UDP协议是否支持HTTP和HTTPS协议?为什么?TCP协议支持吗?

    不多说,直接上干货! 福利 => 每天都推送 欢迎大家,关注微信扫码并加入我的4个微信公众号:   大数据躺过的坑      Java从入门到架构师      人工智能躺过的坑          ...

随机推荐

  1. hibernate的load和get有什么作用

    ① load方法认为该数据在数据库中一定存在,可以放心的使用代理来延迟加载,如果在使用过程中发现了问题,只能抛异常(ObjectNotFoundException)load方法加载实体对象的时候,根据 ...

  2. [LeetCode] 188. Best Time to Buy and Sell Stock IV 买卖股票的最佳时间 IV

    Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...

  3. [LeetCode] 441. Arranging Coins 排列硬币

    You have a total of n coins that you want to form in a staircase shape, where every k-th row must ha ...

  4. 画图前端:mermaid。时序图/类图/甘特图/流程图/状态图/饼图。类似工具:Typora

    文档 https://mermaidjs.github.io/#/ cdn https://www.bootcdn.cn/mermaid/ 在线编辑 https://mermaidjs.github. ...

  5. Django:前后端分离 djangorestframework开发API接口 serializer序列化认证组件

    参考:https://blog.csdn.net/zhangmengran/article/details/84887206 目的: 使用serializer序列化器将QuerySet数据序列化为js ...

  6. Kubernetes 基于 RBAC 的授权(十六)

    目录 一.RBAC介绍 1.1.角色和集群角色 1.2.RoleBinding 和 ClusterRoleBinding 1.3.资源 1.4.主体 二.命令行工具 2.1.kubectl creat ...

  7. py库:pdfminer3k、docx。(PDFf转word)

    安装pdfminer模块: pip install pdfminer3k 安装docx模块: https://www.lfd.uci.edu/~gohlke/pythonlibs/  下载 pytho ...

  8. 第4/7Beta冲刺

    1.团队成员 成员姓名 成员学号 秦裕航 201731062432(组长) 刘东 201731062227 张旭 201731062129 王伟 201731062214 2.SCRU部分 2.1各成 ...

  9. Get Docker Engine - Community for Ubuntu

    Get Docker Engine - Community for Ubuntu Uninstall old versions$ sudo apt-get remove docker docker-e ...

  10. 爬虫请求库之requests库

    一.介绍 介绍:使用requests可以模拟浏览器的请求,比之前的urllib库使用更加方便 注意:requests库发送请求将网页内容下载下来之后,并不会执行js代码,这需要我们自己分析目标站点然后 ...