package com.wonlymall.mall.restfulapi.common.util;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @ClassName: HttpClientUtil
* @Descripton: http请求工具类
*
* @author: wucj
* @date: 2016年5月16日 下午3:42:09
*
* @version 版权 Copyright(c)2015 杭州安必盛技术有限公司
*
*/
public class HttpClientUtil {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
/**
*
* @Description: post请求
*
* @param strUrl
* @param map
* @param encoding
* @return
*/
public static String doPost(String strUrl,Map<String,String> map,String encoding){
String ret = "";
HttpURLConnection conn = null;
try {
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
// 以post方式通信
conn.setRequestMethod("POST");
// 设置请求默认属性
//设置连接超时时间==30s
conn.setConnectTimeout(30 * 1000);
//User-Agent
conn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)");
//不使用缓存
conn.setUseCaches(false);
//允许输入输出
conn.setDoInput(true);
conn.setDoOutput(true);
// Content-Type
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
//参数
String params = "";
if(map != null){
for (Map.Entry<String, String> entry : map.entrySet()) {
params +="&"+entry.getKey()+"="+entry.getValue();
}
}
if(params.startsWith("&") == true){
params = params.substring(1, params.length());
}
//传入
BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());
final int len = 1024; // 1KB
doOutput(out, params.getBytes(), len);
// 关闭流
out.close();
// 获取响应返回状态码
int responseCode = conn.getResponseCode();
if(responseCode == 200){
// 获取应答输入流
InputStream inputStream = conn.getInputStream();
//获取应答内容
ret=inputStreamToStr(inputStream,encoding);
//关闭输入流
inputStream.close();
}else{
logger.error(strUrl+",http post请求失败!!!");
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(conn != null){
conn.disconnect();
}
}
return ret;
}
/**
*
* @Description: get请求
*
* @param strUrl
* @param map
* @param encoding
* @return
*/
public static String doGet(String strUrl,Map<String,String> map,String encoding){
String ret = "";
HttpURLConnection conn = null;
try {
//参数
String params = "";
if(map != null){
for (Map.Entry<String, String> entry : map.entrySet()) {
params +="&"+entry.getKey()+"="+entry.getValue();
}
}
if(params.startsWith("&") == true){
params = params.substring(1, params.length());
}
String surl = strUrl+"?"+params;
URL url = new URL(surl);
conn = (HttpURLConnection) url.openConnection();
// 以post方式通信
conn.setRequestMethod("GET");
// 设置请求默认属性
//设置连接超时时间==30s
conn.setConnectTimeout(30 * 1000);
//User-Agent
conn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)");
//不使用缓存
conn.setUseCaches(false);
//允许输入输出
conn.setDoInput(true);
conn.setDoOutput(true);
// Content-Type
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// 获取响应返回状态码
int responseCode = conn.getResponseCode();
if(responseCode == 200){
// 获取应答输入流
InputStream inputStream = conn.getInputStream();
//获取应答内容
ret=inputStreamToStr(inputStream,encoding);
//关闭输入流
inputStream.close();
}else{
logger.error(surl+":"+responseCode+" ,http get请求失败!!!");
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(conn != null){
conn.disconnect();
}
}
return ret;
}
/**
* 处理输出<br/>
* 注意:流关闭需要自行处理
* @param out
* @param data
* @param len
* @throws IOException
*/
private static void doOutput(OutputStream out, byte[] data, int len)
throws IOException {
int dataLen = data.length;
int off = 0;
while (off < data.length) {
if (len >= dataLen) {
out.write(data, off, dataLen);
off += dataLen;
} else {
out.write(data, off, len);
off += len;
dataLen -= len;
}
// 刷新缓冲区
out.flush();
}
}
/**
* InputStream转换成String
* 注意:流关闭需要自行处理
* @param in
* @param encoding 编码
* @return String
* @throws Exception
*/
private static String inputStreamToStr(InputStream in,String encoding) throws IOException{
int BUFFER_SIZE = 4096;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[BUFFER_SIZE];
int count = -1;
while((count = in.read(data,0,BUFFER_SIZE)) != -1) {
outStream.write(data, 0, count);
}
data = null;
byte[] outByte = outStream.toByteArray();
outStream.close();
return new String(outByte,encoding);
}
public static String doPost(String url,String jsonstr,String charset){
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = new SSLClient();
httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
StringEntity se = new StringEntity(jsonstr);
se.setContentType("text/json");
se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
httpPost.setEntity(se);
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,charset);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}
public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
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();
} catch (ConnectException ce) {
logger.error("Weixin server connection timed out.");
} catch (Exception e) {
logger.error("https request error:{}", e);
}
return buffer.toString();
}
}
HttClientUtil
最新推荐文章于 2022-11-02 10:30:37 发布