HttpClient实战

xiaoxiao2021-02-28  73

HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。现在HttpClient最新版本为 HttpClient 4.5 (GA) 

---------------------------------------------------------------doget-------------------------------------------------------

public static String doGet(String url, Map<String, String> param) {

// 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = ""; CloseableHttpResponse response = null; try { // 创建uri URIBuilder builder = new URIBuilder(url); //URIBuilder包含:协议,主机名,端口(可选),资源路径,和多个参数(可选) if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); } } URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); // 执行请求 response = httpclient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString;

}

------------------------------------------------------------------------doPost-----------------------------------------------

public static String doPost(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (param != null) { List<NameValuePair> paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; }

---------------------------------------------------------------------------- ----------------------------------------------

package com.dt.httpclient; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientDemo { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建httpClient实例  //使用代理  关于代理IP的话 也分几种 透明代理、匿名代理、混淆代理、高匿代理  //----》使用高匿代理  http://www.xicidaili.com/  HttpHost proxy=new HttpHost("219.145.232.204", 8118);       RequestConfig requestConfig=RequestConfig.custom()      .setConnectTimeout(5000)  //设置连接超时      .setSocketTimeout(5000)      .setProxy(proxy)      .build();          HttpGet httpGet = new HttpGet("http://www.xicidaili.com/"); // 创建httpget实例  httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");// 设置请求头消息User-Agent  httpGet.setConfig(requestConfig);  //设置代理服务器    CloseableHttpResponse response = httpClient.execute(httpGet); // 执行http get请求 //服务器内部报错 返回500,  比如这个请求地址不存在 返回404 ,正常情况 执行成功 返回200状态码, System.out.println("Status:"+response.getStatusLine().getStatusCode()); HttpEntity entity = response.getEntity(); // 获取返回实体 System.out.println("Content-Type:"+entity.getContentType().getValue()); System.out.println("网页内容:" + EntityUtils.toString(entity, "utf-8")); // 获取网页内容 System.out.println("-------"+entity.getContent()); response.close(); // response关闭 httpClient.close(); // httpClient关闭 } }

转载请注明原文地址: https://www.6miu.com/read-82996.html

最新回复(0)