importjava.io.IOException;importjava.util.LinkedList;importjava.util.List;importorg.apache.http.Consts;importorg.apache.http.NameValuePair;importorg.apache.http.client.CookieStore;importorg.apache.http.client.config.CookieSpecs;importorg.apache.http.client.config.RequestConfig;importorg.apache.http.client.entity.UrlEncodedFormEntity;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.client.protocol.HttpClientContext;importorg.apache.http.cookie.Cookie;importorg.apache.http.impl.client.BasicCookieStore;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.message.BasicNameValuePair;importorg.apache.http.util.EntityUtils;/*** @auther mxh
* @time 2019/5/20 13:48*/
public classZhiHuTest {public static void main(String[] args) throwsjava.text.ParseException {
String name= "******@qq.com"; // String password = "******"; //
//全局请求设置
RequestConfig globalConfig =RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();//创建cookie store的本地实例
CookieStore cookieStore = newBasicCookieStore();//创建HttpClient上下文
HttpClientContext context =HttpClientContext.create();
context.setCookieStore(cookieStore);//创建一个HttpClient
CloseableHttpClient httpClient =HttpClients.custom().setDefaultRequestConfig(globalConfig)
.setDefaultCookieStore(cookieStore).build();
CloseableHttpResponse res= null;//创建本地的HTTP内容
try{try{//创建一个get请求用来获取必要的Cookie,如_xsrf信息
HttpGet get = new HttpGet("http://www.zhihu.com/");
res=httpClient.execute(get, context);//获取常用Cookie,包括_xsrf信息
System.out.println("访问知乎首页后的获取的常规Cookie:===============");for(Cookie c : cookieStore.getCookies()) {
System.out.println(c.getName()+ ": " +c.getValue());
}
res.close();//构造post数据
List valuePairs = new LinkedList();
valuePairs.add(new BasicNameValuePair("email", name));
valuePairs.add(new BasicNameValuePair("password", password));
valuePairs.add(new BasicNameValuePair("remember_me", "true"));
UrlEncodedFormEntity entity= newUrlEncodedFormEntity(valuePairs, Consts.UTF_8);
entity.setContentType("application/x-www-form-urlencoded");//创建一个post请求
HttpPost post = new HttpPost("https://www.zhihu.com/login/email");//注入post数据
post.setEntity(entity);
res=httpClient.execute(post, context);//打印响应信息,查看是否登陆是否成功
System.out.println("打印响应信息===========");
System.out.println(res.toString());
res.close();
System.out.println("登陆成功后,新的Cookie:===============");for(Cookie c : context.getCookieStore().getCookies()) {
System.out.println(c.getName()+ ": " +c.getValue());
}//构造一个新的get请求,用来测试登录是否成功
HttpGet newGet = new HttpGet("https://www.zhihu.com/question/293207596/answer/684673400");
res=httpClient.execute(newGet, context);
String content=EntityUtils.toString(res.getEntity());
System.out.println("登陆成功后访问的页面===============");
System.out.println(content);
res.close();
}finally{
httpClient.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}