Skip to content

Commit 793cec1

Browse files
committed
HttpClient模拟登录知乎
1 parent c31f1bf commit 793cec1

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Main.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import org.apache.http.Consts;
2+
import org.apache.http.NameValuePair;
3+
import org.apache.http.client.config.CookieSpecs;
4+
import org.apache.http.client.config.RequestConfig;
5+
import org.apache.http.client.entity.UrlEncodedFormEntity;
6+
import org.apache.http.client.methods.CloseableHttpResponse;
7+
import org.apache.http.client.methods.HttpGet;
8+
import org.apache.http.client.methods.HttpPost;
9+
import org.apache.http.impl.client.CloseableHttpClient;
10+
import org.apache.http.impl.client.HttpClients;
11+
import org.apache.http.message.BasicNameValuePair;
12+
import org.apache.http.util.EntityUtils;
13+
14+
import java.io.IOException;
15+
import java.util.LinkedList;
16+
import java.util.List;
17+
18+
public class Main {
19+
public static void main(String[] args) {
20+
RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
21+
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
22+
23+
HttpGet get = new HttpGet("http://www.zhihu.com/");
24+
try {
25+
CloseableHttpResponse response = httpClient.execute(get);
26+
String responseHtml = EntityUtils.toString(response.getEntity());
27+
String xsrfValue = responseHtml.split("<input type=\"hidden\" name=\"_xsrf\" value=\"")[1].split("\"/>")[0];
28+
System.out.println("xsrfValue:" + xsrfValue);
29+
response.close();
30+
List<NameValuePair> valuePairs = new LinkedList<NameValuePair>();
31+
valuePairs.add(new BasicNameValuePair("_xsrf" , xsrfValue));
32+
valuePairs.add(new BasicNameValuePair("email", 用户名));
33+
valuePairs.add(new BasicNameValuePair("password", 密码));
34+
valuePairs.add(new BasicNameValuePair("rememberme", "y"));
35+
36+
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, Consts.UTF_8);
37+
HttpPost post = new HttpPost("http://www.zhihu.com/login");
38+
post.setEntity(entity);
39+
httpClient.execute(post);//登录
40+
41+
HttpGet g = new HttpGet("http://www.zhihu.com/question/following");//获取“我关注的问题”页面
42+
CloseableHttpResponse r = httpClient.execute(g);
43+
System.out.println(EntityUtils.toString(r.getEntity()));
44+
r.close();
45+
} catch (IOException e) {
46+
e.printStackTrace();
47+
} finally {
48+
try {
49+
httpClient.close();
50+
} catch (IOException e) {
51+
e.printStackTrace();
52+
}
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)