最近遇到一个抓取网站数据的问题,普通的抓取,一般直接json解析或者用jsoup解析文档即可,这次遇到的网站首先需要登录,其次传递的参数也有点不一样。

1、首先抓包获取登录的url,新建post请求
HttpClient httpclient = new DefaultHttpClient(); HttpPost httpost = new
HttpPost(url); // 登录url
2、设置用户名和密码参数
List<NameValuePair> nvp = new ArrayList<NameValuePair>(); nvp.add(new
BasicNameValuePair("username", "xxx")); nvp.add(new
BasicNameValuePair("password", "yyy")); String sCharSet = "utf-8";
httpost.setEntity(new UrlEncodedFormEntity(nvp, sCharSet));
3、发起请求
HttpResponse response = httpclient.execute(httpost);
4、获取返回值和cookie
String str = EntityUtils.toString(response.getEntity()); // post请求成功后的返回值
String cookie = response.getLastHeader("Set-Cookie").getValue(); // 获取cookie值
5、新建抓取数据的请求
HttpPost httpost2 = new HttpPost(url2); // 数据接口url
6、设置请求头
httpost2.setHeader("Cookie", cookie); // 设置之前获取到的cookie
httpost2.setHeader("Content-Type", "application/json;charset=UTF-8");
7、通过抓包,得知参数是通过form data方式传递还是通过request payload方式,form data方式就是通过键值对
NameValuePair、UrlEncodedFormEntity的方式,如果是request
payload方式的话,则需要字符流StringEntity的方式了。

// request payload StringEntity entity2 = new StringEntity(jsonString); //
一般是json字符串 httpost2.setEntity(entity2);
8、执行请求就可以获取到我们要的数据了
HttpResponse response2 = httpclient.execute(httpost2); String str =
EntityUtils.toString(response2.getEntity()); // 这里就是我们要的数据了。

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信