HTTP和HTTPS请求

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

image
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容