一、官方网址: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();//关闭流
}