方式一:
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.length; i++) {
System.out.println(heads[i].getName() + "-->" + 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<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
// 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 block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.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;
}