如何从POST请求中检索cookie?

时间:2012-04-28 15:30:23

标签: java cookies httpclient http-post

我可以使用org.apache.http.clien.HttpClient发送POST请求并获取HTTP响应。但是我登录时没有得到HTML内容,因为我的PHP脚本需要cookie。那么,如何在POST请求之后读取POST请求响应的cookie并使用GET请求将其发回?

    HttpClient httpClient = new DefaultHttpClient();

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    nameValuePairs.add(new BasicNameValuePair("username", "user"));  
    nameValuePairs.add(new BasicNameValuePair("password", "passwd"));  

    HttpPost httpPost = new HttpPost("http://localhost/index.php");
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    HttpResponse httpResponse = httpClient.execute(httpPost);

    BufferedInputStream bis = new BufferedInputStream(httpResponse.getEntity().getContent()); // Just gets the HTML content, not the cookies

2 个答案:

答案 0 :(得分:9)

Cookie是标准标题,因此您可以从

获取它
 httpResponse.getHeader("Cookie")

如果您从同一个应用程序调用服务器,则可以让httpclient保持cookie状态。不要每次都创建一个新实例,它应该可以工作。

答案 1 :(得分:3)

如果您使用相同的HTTPClient实例并且您的服务器正在发送正确的标头,则应自动处理它。

请参阅http://hc.apache.org/httpclient-3.x/cookies.html

相关问题