近期这几周。一直在忙同一个项目。刚開始是了解需求。需求有一定了解之后,就開始调第三方的接口。因为第三方给提供的文档非常模糊,在调接口的时候,出了非常多问题,一直在沟通协调,详细的无奈就不说了,因为接口的訪问协议是通过 HTTP 和 HTTPS 通讯的,因此封装了一个简单的请求工具类。因为时间紧迫。并没有额外的时间对工具类进行优化和扩展。假设兴许空出时间的话,我会对该工具类继续进行优化和扩展的。

引用

首先说一下该类中须要引入的 jar 包,apache 的 httpclient 包,版本为 4.5,如有须要的话。可以引一下。

代码

<span style="font-family:Comic Sans MS;">import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** HTTP 请求工具类** @author : liii* @version : 1.0.0* @date : 2015/7/21* @see : TODO*/
public class HttpUtil {private static PoolingHttpClientConnectionManager connMgr;private static RequestConfig requestConfig;private static final int MAX_TIMEOUT = 7000;static {// 设置连接池connMgr = new PoolingHttpClientConnectionManager();// 设置连接池大小connMgr.setMaxTotal(100);connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());RequestConfig.Builder configBuilder = RequestConfig.custom();// 设置连接超时configBuilder.setConnectTimeout(MAX_TIMEOUT);// 设置读取超时configBuilder.setSocketTimeout(MAX_TIMEOUT);// 设置从连接池获取连接实例的超时configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);// 在提交请求之前 測试连接是否可用configBuilder.setStaleConnectionCheckEnabled(true);requestConfig = configBuilder.build();}/*** 发送 GET 请求(HTTP)。不带输入数据* @param url* @return*/public static String doGet(String url) {return doGet(url, new HashMap<String, Object>());}/*** 发送 GET 请求(HTTP)。K-V形式* @param url* @param params* @return*/public static String doGet(String url, Map<String, Object> params) {String apiUrl = url;StringBuffer param = new StringBuffer();int i = 0;for (String key : params.keySet()) {if (i == 0)param.append("?");elseparam.append("&");param.append(key).append("=").append(params.get(key));i++;}apiUrl += param;String result = null;HttpClient httpclient = new DefaultHttpClient();try {HttpGet httpPost = new HttpGet(apiUrl);HttpResponse response = httpclient.execute(httpPost);int statusCode = response.getStatusLine().getStatusCode();System.out.println("运行状态码 : " + statusCode);HttpEntity entity = response.getEntity();if (entity != null) {InputStream instream = entity.getContent();result = IOUtils.toString(instream, "UTF-8");}} catch (IOException e) {e.printStackTrace();}return result;}/*** 发送 POST 请求(HTTP),不带输入数据* @param apiUrl* @return*/public static String doPost(String apiUrl) {return doPost(apiUrl, new HashMap<String, Object>());}/*** 发送 POST 请求(HTTP),K-V形式* @param apiUrl API接口URL* @param params 參数map* @return*/public static String doPost(String apiUrl, Map<String, Object> params) {CloseableHttpClient httpClient = HttpClients.createDefault();String httpStr = null;HttpPost httpPost = new HttpPost(apiUrl);CloseableHttpResponse response = null;try {httpPost.setConfig(requestConfig);List<NameValuePair> pairList = new ArrayList<>(params.size());for (Map.Entry<String, Object> entry : params.entrySet()) {NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());pairList.add(pair);}httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));response = httpClient.execute(httpPost);System.out.println(response.toString());HttpEntity entity = response.getEntity();httpStr = EntityUtils.toString(entity, "UTF-8");} catch (IOException e) {e.printStackTrace();} finally {if (response != null) {try {EntityUtils.consume(response.getEntity());} catch (IOException e) {e.printStackTrace();}}}return httpStr;}/*** 发送 POST 请求(HTTP),JSON形式* @param apiUrl* @param json json对象* @return*/public static String doPost(String apiUrl, Object json) {CloseableHttpClient httpClient = HttpClients.createDefault();String httpStr = null;HttpPost httpPost = new HttpPost(apiUrl);CloseableHttpResponse response = null;try {httpPost.setConfig(requestConfig);StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");//解决中文乱码问题stringEntity.setContentEncoding("UTF-8");stringEntity.setContentType("application/json");httpPost.setEntity(stringEntity);response = httpClient.execute(httpPost);HttpEntity entity = response.getEntity();System.out.println(response.getStatusLine().getStatusCode());httpStr = EntityUtils.toString(entity, "UTF-8");} catch (IOException e) {e.printStackTrace();} finally {if (response != null) {try {EntityUtils.consume(response.getEntity());} catch (IOException e) {e.printStackTrace();}}}return httpStr;}/*** 发送 SSL POST 请求(HTTPS),K-V形式* @param apiUrl API接口URL* @param params 參数map* @return*/public static String doPostSSL(String apiUrl, Map<String, Object> params) {CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();HttpPost httpPost = new HttpPost(apiUrl);CloseableHttpResponse response = null;String httpStr = null;try {httpPost.setConfig(requestConfig);List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());for (Map.Entry<String, Object> entry : params.entrySet()) {NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());pairList.add(pair);}httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));response = httpClient.execute(httpPost);int statusCode = response.getStatusLine().getStatusCode();if (statusCode != HttpStatus.SC_OK) {return null;}HttpEntity entity = response.getEntity();if (entity == null) {return null;}httpStr = EntityUtils.toString(entity, "utf-8");} catch (Exception e) {e.printStackTrace();} finally {if (response != null) {try {EntityUtils.consume(response.getEntity());} catch (IOException e) {e.printStackTrace();}}}return httpStr;}/*** 发送 SSL POST 请求(HTTPS),JSON形式* @param apiUrl API接口URL* @param json JSON对象* @return*/public static String doPostSSL(String apiUrl, Object json) {CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();HttpPost httpPost = new HttpPost(apiUrl);CloseableHttpResponse response = null;String httpStr = null;try {httpPost.setConfig(requestConfig);StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");//解决中文乱码问题stringEntity.setContentEncoding("UTF-8");stringEntity.setContentType("application/json");httpPost.setEntity(stringEntity);response = httpClient.execute(httpPost);int statusCode = response.getStatusLine().getStatusCode();if (statusCode != HttpStatus.SC_OK) {return null;}HttpEntity entity = response.getEntity();if (entity == null) {return null;}httpStr = EntityUtils.toString(entity, "utf-8");} catch (Exception e) {e.printStackTrace();} finally {if (response != null) {try {EntityUtils.consume(response.getEntity());} catch (IOException e) {e.printStackTrace();}}}return httpStr;}/*** 创建SSL安全连接** @return*/private static SSLConnectionSocketFactory createSSLConnSocketFactory() {SSLConnectionSocketFactory sslsf = null;try {SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {return true;}}).build();sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {@Overridepublic boolean verify(String arg0, SSLSession arg1) {return true;}@Overridepublic void verify(String host, SSLSocket ssl) throws IOException {}@Overridepublic void verify(String host, X509Certificate cert) throws SSLException {}@Overridepublic void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {}});} catch (GeneralSecurityException e) {e.printStackTrace();}return sslsf;}/*** 測试方法* @param args*/public static void main(String[] args) throws Exception {}
}</span>

结束语

工具类封装的比較粗糙。兴许还会继续优化的,假设小伙伴们有更好的选择的话,希望也可以分享出来,大家一起学习。

转载于:https://www.cnblogs.com/llguanli/p/8398448.html

HttpClient 发送 HTTP、HTTPS 请求的简单封装相关推荐

  1. HttpClient发送get post请求和数据解析

    最近在跟app对接的时候有个业务是微信登录,在这里记录的不是如何一步步操作第三方的,因为是跟app对接,所以一部分代码不是由我写, 我只负责处理数据,但是整个微信第三方的流程大致都差不多,app端说要 ...

  2. HttpClient发起Http/Https请求工具类

    本文涉及到的主要依赖: <dependency> <groupId>org.apache.httpcomponents</groupId> <artifact ...

  3. vert.x web client发送http https请求

    vert.x web client是一个异步的http客户端,可以很容易的发送异步请求,什么是异步呢?简单举例,同步的http请求,如果服务器没有响应就要一直等着.....异步就是还可以干别的.web ...

  4. 使用httpClient发送get\post请求

    2019独角兽企业重金招聘Python工程师标准>>> maven依赖 1 <dependency> 2 <groupId>org.apache.httpco ...

  5. Go使用HTTPClient发送Get Post请求

    Get请求 url := c.Host + WarningNumreq, err := http.NewRequest("GET", url, nil)q := req.URL.Q ...

  6. android https请求证书过滤白名单,Android处理https请求的证书问题

    android中对部分站点发送https请求会报错,原因是该站点的证书时自定义的,而非官方的,android手机不信任其证书,为了解决这个问题,一般有两种解决方案 忽略证书验证 下载证书到本地,添加到 ...

  7. 十五、Fiddler抓包工具详细教程 — Fiddler抓包HTTPS请求(二)

    ###文章内容有配套的学习视频和笔记都放在了文章末尾### 5.查看证书是否安装成功 方式一: 点击Tools菜单 -> Options... -> HTTPS -> Actions ...

  8. 发送http和https请求工具类 Json封装数据

    在一些业务中我们可要调其他的接口(第三方的接口) 这样就用到我接下来用到的工具类. 用这个类需要引一下jar包的坐标 <dependency><groupId>org.jsou ...

  9. HttpClient发送Https请求报 : unable to find valid certification path to requested target

    一.场景   近期在对接第三方接口时,通过HttpClient发送Https请求报 : unable to find valid certification path to requested tar ...

最新文章

  1. in the java search_Search API – Using scrolls in Java - Elasticsearch Java API 手册
  2. java poi设置单元格格式为数值,Apache POI 如何读取Excel中数值类型单元格所规定的保留小数位?...
  3. idea启动tomcat很慢_idea使用maven创建web项目
  4. 自己封装一个弹框插件
  5. codevs1040 统计单词个数
  6. 数论 —— 毕达哥拉斯三元组
  7. 从谷歌浏览器复制不带样式_文字特效游戏海报特效字体photoshop字体图层样式
  8. 经典算法面试题目-翻转一个C风格的字符串(1.2)
  9. C# 如何在PDF中绘制不同风格类型的文本
  10. Android系统上实现类似按键精灵的效果
  11. 计算机分组Excel,【Excel神技能】如何在Excel表格中进行“数据分组”?
  12. 光缆定位仪光衰点定位光纤识别方法
  13. 【Spring】IoC容器系列的设计与实现:BeanFactory和ApplicationContext
  14. iOS知识点汇总复习
  15. 32个企业软件门类名称和释义
  16. 网上买包包首选的3个网站(必看的3个包包网站)
  17. 【HTML5】HTML语法和基本常用标签(字符集)
  18. 智能化“决战”开启新周期:大众“向上”、蔚来“向下”
  19. Could not find artifact com.dingtalk.api:top-api-sdk-dev:pom:ding-open-mc-SNAPSHOT in aliyunmaven
  20. 给某汉化联盟讲些历史故事

热门文章

  1. python常用api_[原创]IDAPython常用API整理
  2. 平行志愿计算机录取顺序,几张图,看懂平行志愿全部录取过程
  3. python爬虫编码转换_Python 爬虫遇到形如 小说 的编码如何转换为中文? - SegmentFault 思否...
  4. java5.0下载_java虚拟机
  5. 动感灯箱制作流程培训_从事广告行业20年老师傅,揭秘广告牌类型和制作工艺流程 !...
  6. 实木地板被机器人弄成坑_实木地板的常规保养
  7. 自学python需要什么_自学Python编程有什么要求
  8. idea base64encoder没有jar包_老师,免费版的IDEA为啥不能使用Tomcat?
  9. linux c计算两个int相除求百分比的实现
  10. Android实现飘动的旗帜效果实例