HTTPClient示例分享

杨采妮 Java教程 发布时间:2022-05-27 23:21:06 阅读数:3972 1 HttpClient
下文笔者讲述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()
 
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;
    }
 
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaCourse/202205/3545.html

最近发表

热门文章

好文推荐

Java265.com

http://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者