httpclient 简单使用:编写请求头、编写请求参数、获取响应头、获取网页内容
package top.shijialeya.test;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
public class PostTest {
@Test
public void test01() {
//创建 HTTP 客户端
CloseableHttpClient client = HttpClients.createDefault();
//创建 Post 请求对象
HttpPost post = new HttpPost("");
//创建 Post 请求参数集合
ArrayList<BasicNameValuePair> list = new ArrayList<>();
//添加 Post 请求参数和值
list.add(new BasicNameValuePair("username","jiale123"));
list.add(new BasicNameValuePair("password","123456"));
try {
//将请求参数集合添加到请求中
post.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
//添加请求头的参数和值
post.addHeader("Cookie", "123456789");
post.addHeader("User-Agent", "Mozilla AppleWebKit Chrome Safari Edg");
//...
//添加请求配置,设置响应时间等
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(2000) //服务器响应超时时间
.setConnectionRequestTimeout(2000) //连接服务器超时时间
.build();
//将配置信息添加到 post
post.setConfig(requestConfig);
//连接,获得内容
CloseableHttpResponse httpResponse = client.execute(post);
//获得响应头的全部参数
System.out.println("获得响应头的全部参数");
Header[] allHeaders = httpResponse.getAllHeaders();
for (int i = 0; i < allHeaders.length; i++) {
String name = allHeaders[i].getName();
String value = allHeaders[i].getValue();
System.out.println(name + ":" + value);
}
System.out.println();
//获得单个响应头
System.out.println("获得单个响应头");
Header[] headers = httpResponse.getHeaders("Content-Type");
for (Header header : headers) {
System.out.println("Content-Type:" + header);
}
System.out.println();
//获得网页内容
System.out.println("获得网页内容");
HttpEntity entity = httpResponse.getEntity();
//指定字符集
String text = EntityUtils.toString(entity, "utf-8");
System.out.println(text);
} catch (Exception e) {
e.printStackTrace();
} finally {
//资源释放
if (post != null){
try {
post.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
if (client != null){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}