本文使用httpcomponents-client-4.5.3和httpcomponents-core-4.4.6进行CSDN模拟登陆。
//step 1:get some necessary information about login
HttpClientBuilder httpClientBuilder2=HttpClients.custom();
httpClientBuilder2.setUserAgent("");//重要,否者CSDN会拒绝访问
CloseableHttpClient httpClient2=httpClientBuilder2.build();
HttpGet httpGet=new HttpGet("https://passport.csdn.net/account/login");
CloseableHttpResponse response=httpClient2.execute(httpGet);
//这里使用Jsoup第三方包来解析网页
Document document=Jsoup.parse(response.getEntity().getContent(),"utf-8","http://www.csdn.net");
String lt = document.select("#fm1 > input[type='hidden']:nth-child(5)").get(0).val();
String execution=document.select("#fm1 > input[type='hidden']:nth-child(6)").get(0).val();
String eventId=document.select("#fm1 > input[type='hidden']:nth-child(7)").get(0).val();
//step 2:post the login information
HttpPost httpPost=new HttpPost("https://passport.csdn.net/account/login");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", "****"));
nvps.add(new BasicNameValuePair("password", "****"));
nvps.add(new BasicNameValuePair("lt", lt));
nvps.add(new BasicNameValuePair("execution",execution));
nvps.add(new BasicNameValuePair("_eventId", eventId));
httpPost.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
CloseableHttpResponse response2=httpClient2.execute(httpPost);
for (Header header : response2.getAllHeaders()){
System.out.println(header.getName()+" "+header.getValue());
}
System.out.println(response2.getStatusLine().getStatusCode());
System.out.println(IOUtils.toString(response2.getEntity().getContent(),"utf-8"));
//step 3 : visit VIP page
HttpGet httpGetCsdn=new HttpGet("https://my.csdn.net/my/score");
CloseableHttpResponse response3=httpClient2.execute(httpGetCsdn);
System.out.println(response3.getStatusLine().getStatusCode());
System.out.println(IOUtils.toString(response3.getEntity().getContent(),"utf-8"));