0
private static CookieStore cookieStore = new BasicCookieStore();
private HttpClient client = new DefaultHttpClient();
private static HttpContext httpContext = new BasicHttpContext();
public static void main(String[] args) throws Exception {
String url = "http://www.codechef.com";
String account = "http://www.codechef.com/node?destination=node";
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
List<NameValuePair> postParams = http.getFormParams();
sendPost(url, postParams);
}
private void sendPost(String url, List<NameValuePair> postParams)
throws Exception {
HttpPost post = new HttpPost(url);
post.setHeader("Accept","text/plain");
post.setHeader("Accept-Language", "en-US");
post.setHeader("Connection", "keep-alive");
post.setEntity(new UrlEncodedFormEntity(postParams));
HttpResponse response = client.execute(post,httpContext);
List<Cookie> cook=cookieStore.getCookies();
if(cook==null)
System.out.println("Null");
else{
System.out.println(cook.size());
for(Cookie c:cook){
String cookieReader=c.getName()+" = "+c.getValue()+";domain= "+c.getDomain();
System.out.println(cookieReader);
}
}
}
public List<NameValuePair> getFormParams() throws UnsupportedEncodingException {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList.add(new BasicNameValuePair("name","name"));
paramList.add(new BasicNameValuePair("pass","pass"));
return paramList;
}
post方法後,cookie的大小爲0,但我從瀏覽器中檢查,並顯示sessionID cookie。但我無法使用此代碼提取它來驗證用戶身份。謝謝。Cookie未顯示(apache httpclient v4)
一開始調試可能是打印的地方「response.getHeaders(‘曲奇’);」收到'回覆'後立即。也許甚至可以手動將它添加到CookieStore中,並查看'cookieStore.getCookies()'是否返回任何內容。 – andrel
此外,當您檢查瀏覽器中收到的頭文件時,請確保不要混淆POST和GET(即:POST可能不會返回GET將返回的相同頭文件)。你可以插入一行打印出'response.getHeaders(「cookie」);'查看收到的實際cookie標頭。 – andrel