博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
httpclient4.5.2 Post请求支持http和https
阅读量:4690 次
发布时间:2019-06-09

本文共 5511 字,大约阅读时间需要 18 分钟。

先导入所需的jar包,pom.xml

org.springframework.boot
spring-boot-starter-web
org.apache.commons
commons-lang3
3.7
org.apache.httpcomponents
httpclient
4.5.2
io.jsonwebtoken
jjwt
0.9.0

 

写一个工具类 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
paramMaps) { String result = null; HttpPost httpPost = new HttpPost(url); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); try { httpPost.setHeaders(headers); List
pairList = new ArrayList<>(); for (Map.Entry
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
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;@Controllerpublic 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
paramMaps = new HashMap<>(); paramMaps.put("param01", "value01"); String resutlMsg = HttpUtil.doPost(url, headers, paramMaps); System.out.println("return info is : " + resutlMsg); }}

 

好了,备忘一下,需要的朋友可以转载,但请注明原著来源,谢谢。

 

转载于:https://www.cnblogs.com/jimmyshan-study/p/11134671.html

你可能感兴趣的文章
python 二维字典
查看>>
编译原理实验一
查看>>
Git for Android Studio 学习笔记
查看>>
pip 警告!The default format will switch to columns in the future
查看>>
Arrays类学习笔记
查看>>
实验吧之【天下武功唯快不破】
查看>>
2019-3-25多线程的同步与互斥(互斥锁、条件变量、读写锁、自旋锁、信号量)...
查看>>
win7-64 mysql的安装
查看>>
dcm4chee 修改默认(0002,0013) ImplementationVersionName
查看>>
maven3在eclipse3.4.2中创建java web项目
查看>>
发布时间 sql语句
查看>>
黑马程序员 ExecuteReader执行查询
查看>>
记一些从数学和程序设计中体会到的思想
查看>>
题目1462:两船载物问题
查看>>
POJ 2378 Tree Cutting(树形DP,水)
查看>>
第二冲刺阶段个人博客5
查看>>
UVA 116 Unidirectional TSP (白书dp)
查看>>
第三方测速工具
查看>>
MySQL 网络访问连接
查看>>
在aws ec2上使用root用户登录
查看>>