首页 > 代码库 > HttpClient
HttpClient
导入依赖
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version></dependency>
HttpClient API使用
package cn.cslg.httpclient;import java.io.IOException;import org.apache.http.HttpEntity;import org.apache.http.HttpHost;import org.apache.http.ParseException;import org.apache.http.client.ClientProtocolException;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 HttpClinet { public static void main(String[] args) { CloseableHttpClient httpClient=HttpClients.createDefault(); // 创建httpClient实例 HttpGet httpGet=new HttpGet("http://www.tuicool.com"); // 创建httpget实例 HttpHost proxy=new HttpHost("220.166.96.90", 82); // 创建代理主机 RequestConfig config=RequestConfig.custom() .setConnectTimeout(10000) // 设置连接超时时间10秒钟 .setSocketTimeout(10000) // 设置读取超时时间10秒钟 .setProxy(proxy) // 设置代理 .build(); httpGet.setConfig(config); httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"); // 设置头信息,模拟浏览器访问 CloseableHttpResponse response=null; try { response=httpClient.execute(httpGet); //执行http get请求 } catch (ClientProtocolException e) { // http协议异常 // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // io异常 // TODO Auto-generated catch block e.printStackTrace(); } HttpEntity entity=response.getEntity(); // 获取返回实体 try { System.out.println("Status:"+response.getStatusLine().getStatusCode()); // 获取响应状态码 System.out.println("Content-Type:"+entity.getContentType().getValue()); // 获取响应头类型 System.out.println("网页内容:"+EntityUtils.toString(entity, "utf-8")); // 获取网页内容 } catch (ParseException e) { // 解析异常 // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // io异常 // TODO Auto-generated catch block e.printStackTrace(); } try { response.close(); // response关闭 } catch (IOException e) { // io异常 // TODO Auto-generated catch block e.printStackTrace(); } try { httpClient.close(); // httpClient关闭 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
HttpClient
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。