HTTP 请求:
LOG.debug("发送url请求天气API ,url:{}",url);
//CloseableHttpClient httpclient = HttpClients.createDefault();
//HttpGet httpGet = new HttpGet(url);
//RequestConfig requestConfig = RequestConfig.custom()
//.setConnectTimeout(5000).setConnectionRequestTimeout(1000)
//.setSocketTimeout(5000).build();
//httpGet.setConfig(requestConfig);
//CloseableHttpResponse response = httpclient.execute(httpGet);
//LOG.debug("得到的结果:" + response.getStatusLine());//得到请求结果
//HttpEntity entity = response.getEntity();//得到请求回来的数据
//String content = EntityUtils.toString(entity, Charset.forName("UTF-8"));
//LOG.debug("得到请求回来的数据:" + content);//得到请求回来的数据
//return content;
}
HTTPs请求 :
public String sendUrl(String url) {
LOG.debug("发送url请求天气API ,url:{}",url);
CloseableHttpClient httpClient = null;
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
if (httpClient != null) {
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
HttpEntity entity = response.getEntity();
// System.out.println("--------------------------------------");
if (entity != null) {
// System.out.println("Response content length: " + entity.getContentLength());
// System.out.println(EntityUtils.toString(entity));
String str = EntityUtils.toString(entity);
LOG.debug("发送url请求天气API,请求结果为:{} ",str);
EntityUtils.consume(entity);
return str;
}
} finally {
response.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
pom.XML
org.apache.httpcomponents
httpclient