热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

HTTPClient4.5.2工具类

2019独角兽企业重金招聘Python工程师标准方式一:HttpUtilpackagecom.weixinsdk.utils;importjava.io.IOExceptio

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

方式一:

HttpUtil

package com.weixinsdk.utils;import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger; public class HttpUtil {private static Logger log = Logger.getLogger(HttpUtil.class);/*** 发送GET请求* @param isHttps* 是否https* @param url* 请求地址* @return 响应结果*/public static String doGet(boolean isHttps, String url) {CloseableHttpClient httpClient = null;try {if (!isHttps) {httpClient = HttpClients.createDefault();} else {httpClient = createSSLInsecureClient();}HttpGet httpget = new HttpGet(url);// HttpGet设置请求头的两种种方式// httpget.addHeader(new BasicHeader("Connection", "Keep-Alive"));httpget.addHeader("Connection", "Keep-Alive");Header[] heads = httpget.getAllHeaders();for (int i = 0; i " + heads[i].getValue());}CloseableHttpResponse response = httpClient.execute(httpget);// 判断状态行if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {HttpEntity entity = response.getEntity();if (entity != null) {String out = EntityUtils.toString(entity, "UTF-8");return out;}}} catch (ClientProtocolException e) {e.printStackTrace();return null;} catch (IOException e) {e.printStackTrace();return null;} finally {try {if (null != httpClient) {httpClient.close();}} catch (IOException e) {log.error("httpClient.close()异常");}}return null;}/*** 发送POST请求* @param isHttps* 是否https* @param url* 请求地址* @param data* 请求实体内容* @param contentType* 请求实体内容的类型* @return 响应结果*/public static String doPost(boolean isHttps, String url, String data, String contentType) {CloseableHttpClient httpClient = null;try {if (!isHttps) {httpClient = HttpClients.createDefault();} else {httpClient = createSSLInsecureClient();}HttpPost httpPost = new HttpPost(url);// HttpPost设置请求头的两种种方式// httpPost.addHeader(new BasicHeader("Connection", "Keep-Alive"));// httpPost.addHeader("Connection", "Keep-Alive");// UrlEncodedFormEntity处理键值对格式请求参数// List list = new ArrayList();// new UrlEncodedFormEntity(list, "UTF-8");if (null != data) {// StringEntity处理任意格式字符串请求参数StringEntity stringEntity = new StringEntity(data, "UTF-8");stringEntity.setContentEncoding("UTF-8");if (null != contentType) {stringEntity.setContentType(contentType);} else {stringEntity.setContentType("application/json");}httpPost.setEntity(stringEntity);}// 设置请求和传输超时时间RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();httpPost.setConfig(requestConfig);HttpResponse response = httpClient.execute(httpPost);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {HttpEntity entity = response.getEntity();if (entity != null) {String out = EntityUtils.toString(entity, "UTF-8");return out;}}} catch (UnsupportedEncodingException e) {log.error(e);} catch (ClientProtocolException e) {e.printStackTrace();log.error("连接超时:" + url);} catch (IOException e) {e.printStackTrace();log.error("IO异常:" + url);} finally {try {if (null != httpClient) {httpClient.close();}} catch (IOException e) {log.error("httpClient.close()异常");}}return null;}/*** Https请求对象,信任所有证书* * @return CloseableHttpClient*/public static CloseableHttpClient createSSLInsecureClient() {try {SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {// 信任所有public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {return true;}}).build();SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);return HttpClients.custom().setSSLSocketFactory(sslsf).build();} catch (KeyManagementException e) {e.printStackTrace();} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (KeyStoreException e) {e.printStackTrace();}return HttpClients.createDefault();}/*** * 测试doGet方法,获取access_token* @param args*/public static void main(String[] args) {String restu = doGet(true,"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx6c797fccab90c81f&secret=fa226e54468b28ece341c2451142ba0d");System.out.println(restu);}
}

 

方式二:

HTTPClientUtil

package com.weixinsdk.utils;import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;import com.alibaba.fastjson.JSONObject;public class HTTPSUtil {/** * 发起https请求并获取结果 * * @param requestUrl 请求地址 * @param requestMethod 请求方式(GET、POST) * @param outputStr 提交的数据 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) */ public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { // 创建SSLContext对象,并使用我们指定的信任管理器初始化 TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // 从上述SSLContext对象中得到SSLSocketFactory对象 SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); // 设置请求方式(GET/POST) httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // 当有数据需要提交时 if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); // 注意编码格式,防止中文乱码 outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } // 将返回的输入流转换成字符串 InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); // 释放资源 inputStream.close(); inputStream = null; httpUrlConn.disconnect();
// jsonObject = JSONObject.fromObject(buffer.toString());jsonObject = (JSONObject) JSONObject.parse(buffer.toString()); } catch (ConnectException ce) { } catch (Exception e) { } return jsonObject; }
}

发送Http请求,返回Json数据进行解析

/*** * fastjson:Http请求Get返回JSONObject* @param url* @return*/@SuppressWarnings("deprecation")public static com.alibaba.fastjson.JSONObject doGetStr(String url) {DefaultHttpClient httpClient = new DefaultHttpClient();HttpGet httpGet = new HttpGet(url);com.alibaba.fastjson.JSONObject jsonObject = null;try {HttpResponse response = httpClient.execute(httpGet);HttpEntity entity = response.getEntity();if(entity!=null){String result = EntityUtils.toString(entity,"UTF-8");jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return jsonObject;}public static com.alibaba.fastjson.JSONObject doPostStr(String url,String outStr) {DefaultHttpClient httpClient = new DefaultHttpClient();HttpPost httpPost = new HttpPost(url);com.alibaba.fastjson.JSONObject jsonObject = null;httpPost.setEntity(new StringEntity(outStr, "UTF-8"));try {HttpResponse response = httpClient.execute(httpPost);HttpEntity entity = response.getEntity();if(entity!=null){String result = EntityUtils.toString(entity, "UTF-8");jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);}} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return jsonObject;}/*** * Json-lib:Http请求Get返回JSONObject* @param url 请求的url地址* @return*/@SuppressWarnings("deprecation")public static JSONObject doGetStr2(String url) {DefaultHttpClient httpClient = new DefaultHttpClient();HttpGet httpGet = new HttpGet(url);JSONObject jsonObject = null;try {HttpResponse response = httpClient.execute(httpGet);HttpEntity entity = response.getEntity();if(entity!=null){String result = EntityUtils.toString(entity,"UTF-8");jsonObject = JSONObject.fromObject(result);}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return jsonObject;}/*** 使用json-lib的JSONObject实现HttpClient请求,获取JSONObject对象* @param url 请求的url地址* @param outStr 请求的参数* @return*/public static JSONObject doPostStr2(String url,String outStr) {DefaultHttpClient httpClient = new DefaultHttpClient();HttpPost httpPost = new HttpPost(url);JSONObject jsonObject = null;httpPost.setEntity(new StringEntity(outStr, "UTF-8"));try {HttpResponse response = httpClient.execute(httpPost);HttpEntity entity = response.getEntity();if(entity!=null){String result = EntityUtils.toString(entity, "UTF-8");jsonObject = JSONObject.fromObject(result);}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return jsonObject;}


转:https://my.oschina.net/u/3725191/blog/2872497



推荐阅读
  • 本文详细介绍了Java中org.eclipse.ui.forms.widgets.ExpandableComposite类的addExpansionListener()方法,并提供了多个实际代码示例,帮助开发者更好地理解和使用该方法。这些示例来源于多个知名开源项目,具有很高的参考价值。 ... [详细]
  • golang常用库:配置文件解析库/管理工具viper使用
    golang常用库:配置文件解析库管理工具-viper使用-一、viper简介viper配置管理解析库,是由大神SteveFrancia开发,他在google领导着golang的 ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • 技术分享:从动态网站提取站点密钥的解决方案
    本文探讨了如何从动态网站中提取站点密钥,特别是针对验证码(reCAPTCHA)的处理方法。通过结合Selenium和requests库,提供了详细的代码示例和优化建议。 ... [详细]
  • 本文介绍了如何使用JQuery实现省市二级联动和表单验证。首先,通过change事件监听用户选择的省份,并动态加载对应的城市列表。其次,详细讲解了使用Validation插件进行表单验证的方法,包括内置规则、自定义规则及实时验证功能。 ... [详细]
  • 作为一名新手,您可能会在初次尝试使用Eclipse进行Struts开发时遇到一些挑战。本文将为您提供详细的指导和解决方案,帮助您克服常见的配置和操作难题。 ... [详细]
  • 本文详细介绍了如何准备和安装 Eclipse 开发环境及其相关插件,包括 JDK、Tomcat、Struts 等组件的安装步骤及配置方法。 ... [详细]
  • 本文详细介绍了Java中org.neo4j.helpers.collection.Iterators.single()方法的功能、使用场景及代码示例,帮助开发者更好地理解和应用该方法。 ... [详细]
  • 深入解析Spring Cloud Ribbon负载均衡机制
    本文详细介绍了Spring Cloud中的Ribbon组件如何实现服务调用的负载均衡。通过分析其工作原理、源码结构及配置方式,帮助读者理解Ribbon在分布式系统中的重要作用。 ... [详细]
  • 前言--页数多了以后需要指定到某一页(只做了功能,样式没有细调)html ... [详细]
  • 本文详细介绍了Akka中的BackoffSupervisor机制,探讨其在处理持久化失败和Actor重启时的应用。通过具体示例,展示了如何配置和使用BackoffSupervisor以实现更细粒度的异常处理。 ... [详细]
  • 本文详细介绍了Java编程语言中的核心概念和常见面试问题,包括集合类、数据结构、线程处理、Java虚拟机(JVM)、HTTP协议以及Git操作等方面的内容。通过深入分析每个主题,帮助读者更好地理解Java的关键特性和最佳实践。 ... [详细]
  • Android 渐变圆环加载控件实现
    本文介绍了如何在 Android 中创建一个自定义的渐变圆环加载控件,该控件已在多个知名应用中使用。我们将详细探讨其工作原理和实现方法。 ... [详细]
  • 在当前众多持久层框架中,MyBatis(前身为iBatis)凭借其轻量级、易用性和对SQL的直接支持,成为许多开发者的首选。本文将详细探讨MyBatis的核心概念、设计理念及其优势。 ... [详细]
  • 高效解决应用崩溃问题!友盟新版错误分析工具全面升级
    友盟推出的最新版错误分析工具,专为移动开发者设计,提供强大的Crash收集与分析功能。该工具能够实时监控App运行状态,快速发现并修复错误,显著提升应用的稳定性和用户体验。 ... [详细]
author-avatar
mobiledu2502926601
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有