1.对于用HttpClient的
import comcommon.HttpClientConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
/**
* HttpClient工具类
* @author dubooooo@126.com 2017年8月29日
*/
public class HttpClientUtil {
final static private String CHAR_SET = "UTF-8";
public static CloseableHttpClient getCloseableHttpClient() {
return HttpClients.createDefault();
}
public static HttpPost getHttpPost(String url) {
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(HttpClientConfig.getRequestConfig());
return httpPost;
}
public static String execute(HttpPost httpPost) throws Exception {
return execute(httpPost,false);
}
public static String execute(HttpPost httpPost,boolean isHttps) throws Exception {
CloseableHttpClient httpClient=null;
if(isHttps){
httpClient= createSSLClientDefault();
}else
{
httpClient = getCloseableHttpClient();
}
try {
CloseableHttpResponse res = httpClient.execute(httpPost);
return EntityUtils.toString(res.getEntity(), CHAR_SET);
} finally {
httpClient.close();
}
}
static CloseableHttpClient createSSLClientDefault() {
SSLContext sslContext;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
@Override
public boolean isTrusted(X509Certificate[] xcs, String string) {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyStoreException ex) {
ex.printStackTrace();
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
} catch (KeyManagementException ex) {
ex.printStackTrace();
}
return HttpClients.createDefault();
}
}
2.对于用HttpURLConnection的
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class WebUtils {
public static String httpRequest(String token, String sendUrl, String sendType, String postData) {
URL url = null;
HttpURLConnection httpurlconnection = null;
logger.info("HTTPRequest(请求连接是:"+sendUrl+",请求参数是:"+postData+")");
try {
url = new URL(sendUrl);
httpurlconnection = (HttpURLConnection) url.openConnection();
boolean useHttps = sendUrl.startsWith("https");
if (useHttps) {
HttpsURLConnection https = (HttpsURLConnection) httpurlconnection;
trustAllHosts(https);
https.setHostnameVerifier(DO_NOT_VERIFY);
}
httpurlconnection.setRequestMethod(sendType);
if (!"".equals(token) && token != null) {
httpurlconnection.setRequestProperty("Authorization", "Bearer "+token);
}
httpurlconnection.setRequestProperty("Content-Type", "application/json");
httpurlconnection.setDoInput(true);
httpurlconnection.setDoOutput(true);
// 设置http请求超时时间30000毫秒(30秒)
httpurlconnection.setConnectTimeout(30000);
httpurlconnection.setReadTimeout(30000);
httpurlconnection.setUseCaches(true);
if (sendType.equalsIgnoreCase("POST")) {
httpurlconnection.getOutputStream().write(postData.getBytes("UTF-8"));
httpurlconnection.getOutputStream().flush();
httpurlconnection.getOutputStream().close();
}
int code = httpurlconnection.getResponseCode();
if (code == 200) {
//得到输入流
InputStream is = httpurlconnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
StringBuffer sbf = new StringBuffer();
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
}
reader.close();
String rev = sbf.toString();
is.close();
System.out.println("\nAPI返回的结果:\n" + rev);
return rev;
} else {
// http 请求返回非 200状态时处理
return httpurlconnection.getResponseMessage();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpurlconnection != null) {
httpurlconnection.disconnect();
}
}
return null;
}
public static String getAccessToken(String client_id,String client_secret) throws Exception {
RedisUtil redis=RedisUtil.getInstance();
String accessTokenCacheKey = "weixin_"+client_id+"_access_token";
String accessToken = redis.get(accessTokenCacheKey);
if(StringUtils.isBlank(accessToken)){
accessToken = getInterfaceAccessToken(client_id,client_secret);
if(StringUtils.isNotBlank(accessToken)){
redis.putex(accessTokenCacheKey, 3600, accessToken);
}
}
return accessToken;
}
private static String getInterfaceAccessToken(String client_id, String client_secret) throws Exception {
String ACCESS_TOKEN = "";
String tokenResponse = httpRequest(null,Global.getConfig("interface_getToken_url")+"?grant_type=client_credentials&client_id="+client_id+"&client_secret="+client_secret,"GET",null);
if(StringUtils.isNotEmpty(tokenResponse)){
if(JSON.isValidObject(tokenResponse)){
JSONObject jo = JSON.parseObject(tokenResponse);
if(jo.containsKey("access_token")){
ACCESS_TOKEN = jo.getString("access_token");
}
}else{
logger.info("===========("+tokenResponse+")不是json格式================");
}
}
return ACCESS_TOKEN;
}
/**
* 信任所有
* @param connection
* @return
*/
private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
SSLSocketFactory newFactory = sc.getSocketFactory();
connection.setSSLSocketFactory(newFactory);
} catch (Exception e) {
e.printStackTrace();
}
return oldFactory;
}
/**
* 覆盖java默认的证书验证
*/
private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
}};
/**
* 设置不验证主机
*/
private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
}