java通过httpclient抓取需要登录的网站数据
发布时间:2018-03-09 16:09,
浏览次数:449
, 标签:
java
httpclient
最近遇到一个抓取网站数据的问题,普通的抓取,一般直接json解析或者用jsoup解析文档即可,这次遇到的网站首先需要登录,其次传递的参数也有点不一样。
1、首先抓包获取登录的url,新建post请求
HttpClient httpclient = new DefaultHttpClient(); HttpPost httpost = new
HttpPost(url); // 登录url
2、设置用户名和密码参数
List nvp = new ArrayList(); 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 &