小白之Socket网络编程--HttpClient(一)

一、官方网址:http://hc.apache.org/

HttpClient下载:http://hc.apache.org/downloads.cgi

常使用站点(4.5版本):http://hc.apache.org/httpcomponents-client-4.5.x/index.html

官方文档:http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/index.html

Maven的地址:

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>

二、 实例代码

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
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;

public class Demo1_timeout {
	/**
	 * @param args
	 * @throws IOException 
	 * @throws ParseException 
	 * 优点:可以作为方法传入,代码简洁
	 * 缺点:访问国外网站时,容易超时
	 * 功能:HttpClient 连接超时及读取超时
	 */
	public static void main(String[] args) throws ParseException, IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();//创建httpClient实例
		HttpGet httpGet = new HttpGet("http://central.maven.org/maven2/");//创建http的get实例
		
		//HttpClient 使用代理 IP
		//HttpHost proxy = new HttpHost("59.57.149.145",9999);;
		RequestConfig config = RequestConfig.custom()//.setProxy(proxy)
									.setConnectTimeout(1000)//设置连接超时时间10秒钟,单位毫秒
									.setSocketTimeout(10000)//设置读取超时时间10秒钟,单位毫秒
									.build();
		httpGet.setConfig(config);
		
		//设置请求头消息 User-Agent 模拟浏览器
		httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko");
		
		CloseableHttpResponse httpResponse = httpClient.execute(httpGet);//执行http的get请求
		HttpEntity httpEntity = httpResponse.getEntity();//获得返回实体
		if(null != httpEntity){
			System.out.println("getContentType:"+httpEntity.getContentType()+"---getContentType value:"+httpEntity.getContentType().getValue());
			//InputStream input = httpEntity.getContent();
			//FileUtils.copyToFile(input, new File("E:\\学习文档\\[www.java1234.com]一头扎进HttpClient视频教程/12.gif"));
		}
//		String str = EntityUtils.toString(httpEntity, "utf-8");//获取网页内容
//		System.out.println("网页内容:"+str);
		httpResponse.close();//关闭流
		httpClient.close();//关闭流
	}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值