package com.itheima.demo02_httpclient;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
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 java.util.ArrayList;
import java.util.List;
/*
案例: 演示通过 HttpClient(浏览器对象), 获取数据. post方式
思路:
1. 明确首页URL.
2. 发送请求, 获取数据.
3. 解析数据.
4. 释放资源.
细节:
使用HttpClient对象之前, 记得要先导包, 我们用的是: 4.5.4版本.
*/
public class Demo02 {
public static void main(String[] args) throws Exception{
//1. 明确首页URL.
String indexUrl = "http://www.itcast.cn";
//2. 发送请求, 获取数据.
//2.1 创建HttpClient对象, 即: 浏览器对象.
CloseableHttpClient httpClient = HttpClients.createDefault();
//2.2 创建HttpPost对象, 用来封装具体的 要发送的数据(请求 行头体).
HttpPost httpPost = new HttpPost(indexUrl);
//2.3 设置请求头信息, 即: 标明是什么浏览器
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362");
//细节: 设置请求体
//创建List集合, 用来存储 Post方式的请求体参数.
//BasicNameValuePair: 请求体参数的格式类型
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
//把具体的提交参数, 添加到List集合中.
list.add(new BasicNameValuePair("username", "liuyifei"));
list.add(new BasicNameValuePair("password", "pw111"));
list.add(new BasicNameValuePair("age", "33"));
//创建具体的请求体对象.
UrlEncodedFormEntity requestEntity = new UrlEncodedFormEntity(list);
//设置请求体.
httpPost.setEntity(requestEntity);
//2.4 发送请求, 获取数据(响应对象)
CloseableHttpResponse response = httpClient.execute(httpPost);
//2.5 判断响应状态码是否是200, 如果是, 表示: 响应成功.
if (response.getStatusLine().getStatusCode() == 200) {
//2.6 获取响应头信息, 并打印.
//Header[] allHeaders = response.getAllHeaders();
//Header[] headers = response.getHeaders("具体的响应头的名字");
//2.7 获取具体的响应体对象.
HttpEntity responseEntity = response.getEntity();
//2.8 从响应体对象中获取具体的数据, 并打印.
System.out.println(EntityUtils.toString(responseEntity, "utf-8"));
}
//3. 解析数据.
//4. 释放资源.
response.close();
httpClient.close();
}
}