packagecom.geturl;importnet.sf.json.JSONObject;importorg.apache.commons.lang.StringUtils;importorg.apache.http.HttpResponse;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClientBuilder;importorg.apache.http.protocol.HTTP;importorg.apache.http.util.EntityUtils;import javax.net.ssl.*;importjavax.servlet.http.HttpServletRequest;importjava.io.ByteArrayOutputStream;importjava.io.InputStream;importjava.net.URL;importjava.security.cert.CertificateException;importjava.security.cert.X509Certificate;public classPostUtil {/***
*@paramurl 这个只支持http地址,不支持https
*@paramrequest
*@return
*/
public staticString sendMessage(String url, HttpServletRequest request) {
CloseableHttpClient httpClient=HttpClientBuilder.create().build();
HttpGet httpGet= new HttpGet(url); //url:请求地址 get请求
httpGet.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8");try{
HttpResponse res=httpClient.execute(httpGet);
String rtn=EntityUtils.toString(res.getEntity());returnrtn;
}catch(Exception e) {
e.printStackTrace();
}finally{
httpGet.releaseConnection();
}return null;
}/***
*
*@paramurl 支持https格式 get请求
*@return返回json格式*/
public staticJSONObject getHttps(String hsUrl) {try{
URL url;
url= newURL(hsUrl);
HttpsURLConnection con=(HttpsURLConnection) url.openConnection();
X509TrustManager xtm= newX509TrustManager() {
@OverridepublicX509Certificate[] getAcceptedIssuers() {//TODO Auto-generated method stub
return null;
}
@Overridepublic voidcheckServerTrusted(X509Certificate[] arg0, String arg1)throwsCertificateException {//TODO Auto-generated method stub
}
@Overridepublic voidcheckClientTrusted(X509Certificate[] arg0, String arg1)throwsCertificateException {//TODO Auto-generated method stub
}
};
TrustManager[] tm={xtm};
SSLContext ctx= SSLContext.getInstance("TLS");
ctx.init(null, tm, null);
con.setSSLSocketFactory(ctx.getSocketFactory());
con.setHostnameVerifier(newHostnameVerifier() {
@Overridepublic booleanverify(String arg0, SSLSession arg1) {return true;
}
});
InputStream inStream=con.getInputStream();
ByteArrayOutputStream outStream= newByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer,0, len);
}byte[] b = outStream.toByteArray();//网页的二进制数据
outStream.close();
inStream.close();
String rtn= new String(b, "utf-8");if(StringUtils.isNotBlank(rtn)) {
JSONObject object=JSONObject.fromObject(rtn);returnobject;
}
}catch(Exception e) {
e.printStackTrace();
}return null;
}
}