HTTPClient示例分享

java 文章 2022-07-21 23:40 393 0 全屏看文

AI助手支持GPT4.0

转自:

http://www.java265.com/JavaCourse/202205/3545.html

下文笔者讲述HTTPClient的示例分享,如下所示

HttpClient简介

HTTPClient:
    是Apache旗下的产品,基于HttpCore
HttpClient的官方参照文档:http://hc.apache.org/httpcomponents-client-ga/tutorial/pdf/httpclient-tutorial.pdf

HttpClient使用步骤:
    1.创建一个CloseableHttpClient实例 
    2.找一个可用的链接(uri)
    3.执行httpclient.execute(uri)
    4.response.close()

HttpClient的特性及优点

1. 基于java语言,实现了Http1.0和Http1.1

2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)

3. 支持HTTPS协议

4. 通过Http代理建立透明的连接

5. 利用CONNECT方法通过Http代理建立隧道的https连接

6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案

7. 插件式的自定义认证方案。

8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案

9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。

10. 自动处理Set-Cookie中的Cookie

11. 插件式的自定义Cookie策略

12. Request的输出流可以避免流中内容直接缓冲到socket服务器

13. Response的输入流可以有效的从socket服务器直接读取相应内容

14. 在http1.0和http1.1中利用KeepAlive保持持久连接

15. 直接获取服务器发送的response code和 headers

16. 设置连接超时的能力

17. 实验性的支持http1.1 response caching

18. 源代码基于Apache License 可免费获取

   使用HttpClient访问指定url

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
<...>
} finally {
response.close();
}

例2:
spring中实例化CloseableHttpClient

@Autowired(required=false)
private CloseableHttpClient httpClient;
 
然后在spring里建一个xml文件专门用于httpClient
关于URI的创建,官方提供了专门的api:

HttpClient provides URIBuilder utility class to simplify creation and modification of request URIs
 
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.google.com")
.setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "")
.build();
HttpGet httpget = new HttpGet(uri);
 
HttpEntity entity = response.getEntity();

例3:
get请求的示例

public String doGet(String url,Map<String, String> params,String encode) throws Exception {
        if(null != params){
            URIBuilder builder = new URIBuilder(url);
            for (Map.Entry<String, String> entry : params.entrySet()) {
   builder.setParameter(entry.getKey(), entry.getValue());
            }
            url = builder.build().toString();
        }
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
   if(encode == null){
       encode = "UTF-8";
   }
   return EntityUtils.toString(response.getEntity(), encode);
            }
        } finally {
            if (response != null) {
   response.close();
            }
        }
        return null;
    }
-EOF-

AI助手支持GPT4.0