如何从POST请求中检索cookie?

Rox*_*Rox 5 java cookies httpclient http-post

我可以使用发送POST请求org.apache.http.clien.HttpClient并获取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
Run Code Online (Sandbox Code Playgroud)

Bru*_*owe 9

cookies是一个标准的标题,所以你可以从中得到它

 httpResponse.getHeader("Cookie")
Run Code Online (Sandbox Code Playgroud)

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

  • 字符串 cookie = httpResponse.getFirstHeader("Cookie").getValue(); (2认同)