HttpClient之请求参数

代码:

package cn.itcast.crawler.test;

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

import java.io.IOException;

public class HttpConfigTest {
public static void main(String[] args) {
//1.创建HttpClient对象
CloseableHttpClient httpClient= HttpClients.createDefault();
//2.创建HttpGet对象,设置URL地址
HttpGet httpGet=new HttpGet("https://www.baidu.com");

//配置请求信息
RequestConfig config=RequestConfig.custom().setConnectTimeout(1000)//创建连接的最长时间,单位是毫秒
.setConnectionRequestTimeout(500) //设置获取连接的最长时间
.setSocketTimeout(10*1000).build(); //设置数据传输的最长时间
//给请求设置请求信息
httpGet.setConfig(config);


//使用httpClient发起响应获取repsonse
CloseableHttpResponse response=null;
try {
response=httpClient.execute(httpGet);
//4.解析响应,获取数据
//判断状态码是否是200
if(response.getStatusLine().getStatusCode()==200){
HttpEntity httpEntity=response.getEntity();
String content=EntityUtils.toString(httpEntity,"utf8");
System.out.println(content.length());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
}

在这以get请求进行测试,设置背景颜色的就是配置请求信息的核心代码,这里只是设置了一部分,我们还可以设置很多,比如设置代理等
上一篇:Httpclient工具类封装


下一篇:Dotnet Core IHttpClientFactory深度研究