Java 如何从POST请求中检索cookies?
我可以使用Java 如何从POST请求中检索cookies?,java,cookies,httpclient,http-post,Java,Cookies,Httpclient,Http Post,我可以使用org.apache.http.clien.HttpClient发送POST请求并获得http响应。但是我在登录时没有得到HTML内容,因为我的PHP脚本需要cookie。那么,如何读取POST请求响应的cookie,并在POST请求之后使用GET请求将其发送回去呢 HttpClient httpClient = new DefaultHttpClient(); List<NameValuePair> nameValuePairs = new ArrayL
org.apache.http.clien.HttpClient
发送POST请求并获得http响应。但是我在登录时没有得到HTML内容,因为我的PHP脚本需要cookie。那么,如何读取POST请求响应的cookie,并在POST请求之后使用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
HttpClient-HttpClient=newdefaulthttpclient();
List nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“用户名”、“用户”));
添加(新的BasicNameValuePair(“密码”、“密码”));
HttpPost HttpPost=新的HttpPost(“http://localhost/index.php");
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse HttpResponse=httpClient.execute(httpPost);
BufferedInputStream bis=新的BufferedInputStream(httpResponse.getEntity().getContent());//只获取HTML内容,而不是cookies
如果您使用相同的HTTPClient实例,并且您的服务器正在发送正确的头,则应该自动处理该实例
请参见Cookie是一个标准标题,因此您可以从
httpResponse.getHeader("Cookie")
如果您希望从同一应用程序调用服务器,那么可以让httpclient维护cookie状态,而不是。不要每次都创建一个新实例,它应该可以工作。String cookie=httpResponse.getFirstHeader(“cookie”).getValue();如果您需要解码服务器发送的Cookie,它是http响应.getHeaders(“Set Cookie”)