多语言展示
当前在线:1640今日阅读:159今日分享:18

利用HttpClient 4.5实现http与https请求

从HttpClient 4.0版本开始,包中的不少方法已过时(deprecated),过时的方法我们一般就不再使用了。现在我向大家介绍如何利用apache提供的HttpClient最新jar包实现http与https的请求
工具/原料
1

Intellij IDEA 14.1.4

2

HttpClient-4.5.jar等一系列的工具包

方法/步骤
1

http实现get请求:首先设置全局的标准cookie策略RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();设置可关闭的httpclientCloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();发送get请求

2

http实劫夏现post请求:首先设置全局的标准cookie策略RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();设置可关闭的httpclientCloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();对请求参数进行编码后再进行发送

3

https网站一般情况下使用了安全系数较低的SHA-1签名,因此首先我们在调用SSL之前需要重写验证方法,取消检测SSL。压冲关

4

https实现get请求施怕:创建可用SchemeRegistry socketFactoryRegistry = RegistryBuilder.create()        .register('http', PlainConnectionSocketFactory.INSTANCE).register('https', socketFactory).build();创建ConnectionManager,添加Connection配置信息PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)        .setDefaultRequestConfig(defaultRequestConfig).build();发送get请求

5

https实现post请求:创建可用SchemeRegistry socketFactoryRegistry = RegistryBuilder.create()       .register('http', PlainConnectionSocketFactory.INSTANCE).register('https', socketFactory).build();创建ConnectionManager,添加Connection配置信息PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)       .setDefaultRequestConfig(defaultRequestConfig).build();对请求参数进行编码后再进行发送

注意事项

调用上面的方法得到response对象后,利用EntityUtils.toString(response.getEntity())可获取到响应数据,同时不要忘了在使用完后关闭,一般我们直接用try(){}的方式自动关闭

推荐信息