时间:2023-1-17 作者:老大夫 分类: 传智JAVA爬虫学习笔记
这节课的地址不能用了,所以post请求返回的的不是200而是403
package cn.itcast.crawler.test;
import com.sun.org.glassfish.gmbal.NameValue;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class HttpPostParamTest {
public static void main(String[] args)throws Exception {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建HttpGet对象,url访问地址
HttpPost httpPost = new HttpPost("http://yun.itheima.com/search");
//声明list集合,封装表单中的参数
List<NameValuePair> params=new ArrayList<NameValuePair>();
//设置请求地址是: https://yun.itheima.com/search?keys=Java
params.add(new BasicNameValuePair("keys","Java"));
//创建表单的Entity对象,第一个是封装好的表单数据,第二个是字符编码
UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(params, Charset.forName("utf8"));
//设置表单的Entity对象到post
httpPost.setEntity(formEntity);
CloseableHttpResponse response = null;
try {
//使用HttpClient发起请求,获取response
response = httpClient.execute(httpPost);
//解析响应
if(response.getCode()==200){
String content = EntityUtils.toString(response.getEntity(), "utf8");
System.out.println(content.length());
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//关闭response
try {
response.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//解析响应
}
}
推荐阅读: