刚写出来的,还未经测试,

HttpUtil.java

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.apache.http.HttpEntity;

import org.apache.http.HttpStatus;

import org.apache.http.NameValuePair;

import org.apache.http.ParseException;

import org.apache.http.client.ClientProtocolException;

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.client.utils.URLEncodedUtils;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.util.EntityUtils;

/**

* HTTP工具类

* 发送http/https协议get/post请求,发送map,json,xml,txt数据

* @author happyqing

* @since 2017-04-08

*/

public final class HttpUtil {

private static Log log = LogFactory.getLog(HttpUtil.class);

/**

* 执行一个http/https get请求,返回请求响应的文本数据

*

* @param url请求的URL地址,可以带参数?param1=a&parma2=b

* @param headerMap请求头参数map,可以为null

* @param paramMap请求参数map,可以为null

* @param charset字符集

* @param pretty是否美化

* @return 返回请求响应的文本数据

*/

public static String doGet(String url, Map headerMap, Map paramMap, String charset, boolean pretty) {

//StringBuffer contentSb = new StringBuffer();

String responseContent = "";

// http客户端

CloseableHttpClient httpclient = null;

// Get请求

HttpGet httpGet = null;

// http响应

CloseableHttpResponse response = null;

try {

if(url.startsWith("https")){

httpclient = HttpsSSLClient.createSSLInsecureClient();

} else {

httpclient = HttpClients.createDefault();

}

// 设置参数

if (paramMap != null) {

List nvps = new ArrayList ();

for (Map.Entry entry : paramMap.entrySet()) {

nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));

}

//EntityUtils.toString(new UrlEncodedFormEntity(nvps, charset));

url = url + "?" + URLEncodedUtils.format(nvps, charset);

}

// Get请求

httpGet = new HttpGet(url); // HttpUriRequest httpGet

// 设置header

if (headerMap != null) {

for (Map.Entry entry : headerMap.entrySet()) {

httpGet.addHeader(entry.getKey(), entry.getValue());

}

}

// 发送请求,返回响应

response = httpclient.execute(httpGet);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

HttpEntity entity = response.getEntity();

//BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset));

// String line;

// while ((line = reader.readLine()) != null) {

// if (pretty)

// contentSb.append(line).append(System.getProperty("line.separator"));

// else

// contentSb.append(line);

// }

//reader.close();

responseContent = EntityUtils.toString(entity, charset);

}

// EntityUtils.consume(entity);

} catch (ClientProtocolException e) {

log.error(e.getMessage(), e);

} catch (IOException e) {

log.error(e.getMessage(), e);

} catch (ParseException e) {

log.error(e.getMessage(), e);

} finally {

try {

if(response!=null){

response.close();

}

if(httpGet!=null){

httpGet.releaseConnection();

}

if(httpclient!=null){

httpclient.close();

}

} catch (IOException e) {

log.error(e.getMessage(), e);

}

}

return responseContent;

}

/**

* 执行一个http/https post请求,返回请求响应的文本数据

*

* @param url请求的URL地址,可以带参数?param1=a&parma2=b

* @param headerMap请求头参数map,可以为null

* @param paramMap请求参数map,可以为null

* @param charset字符集

* @param pretty是否美化

* @return 返回请求响应的文本数据

*/

public static String doPost(String url, Map headerMap, Map paramMap, String charset, boolean pretty) {

//StringBuffer contentSb = new StringBuffer();

String responseContent = "";

// http客户端

CloseableHttpClient httpclient = null;

// Post请求

HttpPost httpPost = null;

// http响应

CloseableHttpResponse response = null;

try {

if(url.startsWith("https")){

httpclient = HttpsSSLClient.createSSLInsecureClient();

} else {

httpclient = HttpClients.createDefault();

}

// Post请求

httpPost = new HttpPost(url);

// 设置header

if (headerMap != null) {

for (Map.Entry entry : headerMap.entrySet()) {

httpPost.addHeader(entry.getKey(), entry.getValue());

}

}

// 设置参数

if (paramMap != null) {

List nvps = new ArrayList ();

for (Map.Entry entry : paramMap.entrySet()) {

nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));

}

httpPost.setEntity(new UrlEncodedFormEntity(nvps, charset));

}

// 发送请求,返回响应

response = httpclient.execute(httpPost);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

HttpEntity entity = response.getEntity();

//BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset));

// String line;

// while ((line = reader.readLine()) != null) {

// if (pretty)

// contentSb.append(line).append(System.getProperty("line.separator"));

// else

// contentSb.append(line);

// }

//reader.close();

responseContent = EntityUtils.toString(entity, charset);

}

// EntityUtils.consume(entity);

} catch (UnsupportedEncodingException e) {

log.error(e.getMessage(), e);

} catch (ClientProtocolException e) {

log.error(e.getMessage(), e);

} catch (IOException e) {

log.error(e.getMessage(), e);

} catch (ParseException e) {

log.error(e.getMessage(), e);

} finally {

try {

if(response!=null){

response.close();

}

if(httpPost!=null){

httpPost.releaseConnection();

}

if(httpclient!=null){

httpclient.close();

}

} catch (IOException e) {

log.error(e.getMessage(), e);

}

}

return responseContent;

}

/**

* 执行一个http/https post请求, 直接写数据 json,xml,txt

*

* @param url请求的URL地址

* @param headerMap请求头参数map,可以为null

* @param contentjson或xml等字符串内容

* @param charset字符集

* @param pretty是否美化

* @return返回请求响应的文本数据

*/

public static String writePost(String url, Map headerMap, String content, String charset, boolean pretty) {

//StringBuffer contentSb = new StringBuffer();

String responseContent = "";

// http客户端

CloseableHttpClient httpclient = null;

// Post请求

HttpPost httpPost = null;

// http响应

CloseableHttpResponse response = null;

try {

if(url.startsWith("https")){

httpclient = HttpsSSLClient.createSSLInsecureClient();

} else {

httpclient = HttpClients.createDefault();

}

// Post请求

httpPost = new HttpPost(url);

// 设置header

if (headerMap != null) {

for (Map.Entry entry : headerMap.entrySet()) {

httpPost.addHeader(entry.getKey(), entry.getValue());

}

}

// 字符串Entity

StringEntity stringEntity = new StringEntity(content, charset);

stringEntity.setContentType("text/plain"); //application/json,text/xml,text/plain

httpPost.setEntity(stringEntity);

// 发送请求,返回响应

response = httpclient.execute(httpPost);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

HttpEntity entity = response.getEntity();

//BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset));

// String line;

// while ((line = reader.readLine()) != null) {

// if (pretty)

// contentSb.append(line).append(System.getProperty("line.separator"));

// else

// contentSb.append(line);

// }

//reader.close();

responseContent = EntityUtils.toString(entity, charset);

}

// EntityUtils.consume(entity);

} catch (UnsupportedEncodingException e) {

log.error(e.getMessage(), e);

} catch (ClientProtocolException e) {

log.error(e.getMessage(), e);

} catch (IOException e) {

log.error(e.getMessage(), e);

} catch (ParseException e) {

log.error(e.getMessage(), e);

} finally {

try {

if(response!=null){

response.close();

}

if(httpPost!=null){

httpPost.releaseConnection();

}

if(httpclient!=null){

httpclient.close();

}

} catch (IOException e) {

log.error(e.getMessage(), e);

}

}

return responseContent;

}

// 通过code获取openId

public static String getOpenId(String code) {

if (StringUtils.isNotEmpty(code)) {

String appid = PropertiesUtil.getProperty("wx.appid");

String secret = PropertiesUtil.getProperty("wx.appsecret");

String result = HttpUtil.doGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code", null, null, "UTF-8",true);

if (StringUtils.isNotEmpty(result)) {

JSONObject json = JSONObject.fromObject(result);

if (json.get("openid") != null) {

return json.get("openid").toString();

}

}

}

return "";

}

public static void main(String[] args) {

try {

String y = doGet("http://video.sina.com.cn/life/tips.html", null, null, "GBK", true);

System.out.println(y);

// String accessToken = HttpUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret", null, null, "UTF-8", true);

// System.out.println(accessToken);

// Map params = new HashMap();

// params.put("param1", "value1");

// params.put("json", "{\"aa\":\"11\"}");

// String j = doPost("http://localhost/uplat/manage/test.do?reqCode=add", null, params, "UTF-8", true);

// System.out.println(j);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

HttpsSSLClient.java

import java.security.KeyManagementException;

import java.security.NoSuchAlgorithmException;

import java.security.SecureRandom;

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;

import javax.net.ssl.SSLContext;

import javax.net.ssl.SSLSession;

import javax.net.ssl.TrustManager;

import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

/**

* 创建httpsclient

* @author happyqing

* @since 2017-04-07

*/

public class HttpsSSLClient {

/**

* 获取Https 请求客户端

* @return

*/

public static CloseableHttpClient createSSLInsecureClient() {

SSLContext sslcontext = createSSLContext();

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new HostnameVerifier() {

@Override

public boolean verify(String paramString, SSLSession paramSSLSession) {

return true;

}

});

CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

return httpclient;

}

/**

* 获取初始化SslContext

* @return

*/

private static SSLContext createSSLContext() {

SSLContext sslcontext = null;

try {

sslcontext = SSLContext.getInstance("TLS");

sslcontext.init(null, new TrustManager[] {new TrustAnyTrustManager()}, new SecureRandom());

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (KeyManagementException e) {

e.printStackTrace();

}

return sslcontext;

}

/**

* 自定义静态私有类

*/

private static class TrustAnyTrustManager implements X509TrustManager {

public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

public X509Certificate[] getAcceptedIssuers() {

return new X509Certificate[] {};

}

}

}

参考:

httpclient4.x处理https协议请求

http://www.oschina.net/code/snippet_2376242_50816#74195

HttpClient_4 用法 由HttpClient_3 升级到 HttpClient_4 必看

http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113252.html

用httpclient4.x 发送http get post请求。

http://blog.csdn.net/sunny243788557/article/details/8106265

HttpClient-4.3.X 中get和post方法使用

http://www.cnblogs.com/520playboy/p/6344940.html

HttpGet &&HttpPost方法发送header,params, Content

http://blog.csdn.net/fhlkm/article/details/7844509

httpf发送 json_Java用HttpClient4发送http/https协议get/post请求,发送map,json,xml,txt数据...相关推荐

  1. httpf发送 json_Java用HttpClient3发送http/https协议get/post请求,发送map,json,xml,txt数据...

    使用的是httpclient 3.1, 使用"httpclient"4的写法相对简单点,百度:httpclient https post 当不需要使用任何证书访问https网页时, ...

  2. tomcat 将http协议改为https协议,Websocket请求ws协议修改为wss协议

    tomcat 将http协议改为https协议,Websocket请求ws协议修改为wss协议 一. 说明 WS协议和WSS协议两个均是WebSocket协议的SCHEM,两者一个是非安全的,一个是安 ...

  3. Kafka请求发送分析

    随便写写T_T,本来是想分析Conenct是如何组建集群的,但是写着写着发现分析了请求是如何发送的和回收的.后面也不打算改,就当作是从Connect出发分析Kafka请求是如何发送. 顺带一句,本文只 ...

  4. HTTP和HTTPS协议的区别

    什么是HTTPS: HTTPS(Secure Hypertext Transfer Protocol)安全超文本传输协议 它是一个安全通信通道,它基于HTTP开发,用于在客户计算机和服务器之间交换信息 ...

  5. HTTP协议和HTTPS协议初探

    概况 HTTP是hypertext transfer protocol(超文本传输协议)的简写,它是TCP/IP协议的一个应用层协议,用于定义WEB浏览器与WEB服务器之间交换数据的过程. HTTP是 ...

  6. HTTP 和 HTTPS 协议

    HTTP协议是什么? 简单来说,就是一个基于应用层的通信规范:双方要进行通信,大家都要遵守一个规范,这个规范就是HTTP协议. HTTP协议能做什么? 很多人首先一定会想到:浏览网页.没错,浏览网页是 ...

  7. 【网络协议趣谈】HTTPS协议加密证书和工作模式

    用HTTP协议,看个新闻还没有问题,但是换到更加严肃的场景中就存在很多的安全风险. 例如,下单做一次支付,如果还是使用普通的HTTP协议,那很可能会被黑客盯上 发送一个请求说要点个外卖,但是这个网络包 ...

  8. 【计算机网络】--- HTTP与HTTPS协议详解

    HTTP与HTTPS协议详解 一.URL 二.HTTP协议 三.HTTPS协议 四.HTTP与HTTPS区别(重中之重) 五.如何正确选择HTTP协议和HTTPS协议 引言:当我们打开一个网页时,奇妙 ...

  9. HTTPS网站发起HTTP请求

    ​ 问题 Https网站中无法请求Http资源(静态资源.接口等) https网站发起的http请求会被blocked,不被允许,因此,通过设置nginx反向代理转发http请求. Nginx反向代理 ...

最新文章

  1. 中国移动宽带业务怎么样?和电信的比有什么不同?
  2. 品尝阿里云容器服务:5个2核4G节点使用情况记载
  3. 一张图搞定SDF的概念
  4. 深度优先遍历 java
  5. C#面试题整理(不带答案)
  6. ora-28500 ora-02063 mysql_oracle dblink mysql 报错ORA-28500
  7. Java并发编程-常用的辅助类
  8. 实战Python:详解利用Python和Pygame实现飞机大战
  9. python之模块 os
  10. linux chmod命令
  11. 民间借贷、网贷vs信用卡
  12. 贪心宝贝话说上回讲到海东集团面临内外交困,公司的元老也只剩下XHD夫妇二人了。显然,作为多年拼搏的商人,XHD不会坐以待毙的。 一天,当他正在苦思冥想解困良策的时候,突然想到了自己的传家宝,那是公司成
  13. ARM处理器对比分析
  14. Android基础入门教程——2.4.2 ListView简单使用
  15. Unable to boot device in current state: Creating
  16. oracle 电子书大全
  17. 为ipad搭建code-server服务
  18. TICA 2019 基于人工智能的模型驱动测试设计
  19. 黑马程序员——结缘黑马
  20. 数学建模——核军备竞赛

热门文章

  1. 搜狗推送接口之搜狗收录怎么做?
  2. 2876: 吃货排排坐
  3. Elo第四代触摸一体机发布,助力全场景数字化转型
  4. html语音输入功能讯飞,win10系统利用讯飞语音输入法实现电脑语音输入的方案介绍...
  5. NETCore项目报错 An error occurred while starting the application
  6. 灾难恢复_有效的灾难恢复计划的10个技巧
  7. python输入文字垂直输出_python中len用法-python计算数学表达式-利用python如何垂直输出文字...
  8. 面试题:不通过构造函数也能创建对象吗
  9. IBM X3650 M4 服务器维修 面板BOARD闪黄灯 SYS BRD ERR主板报错
  10. 阵列信号DOA估计系列(二).导向矢量与空间FFT(附代码)