HTTPClient示例分享
下文笔者讲述HTTPClient的示例分享,如下所示
spring中实例化CloseableHttpClient
get请求的示例
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; }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。