我已经使用 HttpRequest 获得了正确的登录信息。它在我的 toast 中打印正确的 html 形式的登录页面(仅用于测试)。现在我想根据该请求设置一个 cookie。这怎么可能? 如果有必要,我可以提供一些代码。
我已经知道 CookieManager 类,但是我怎样才能成功呢?
提前致谢!
我的代码:
public String getPostRequest(String url, String user, String pass) {
HttpClient postClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("login", user));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
response = postClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
instream.close();
return result;
}
}
} catch (Exception e) {}
Toast.makeText(getApplicationContext(),
"Connection failed",
Toast.LENGTH_SHORT).show();
return null;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
嗯,差不多就是这样了。 convertStreamToString() 函数将 InputStream 转换为一个 String(纯 HTML 代码),我将其“烤”出来只是为了测试它(因此它可以工作),所以代码可以正常工作。现在设置cookie。 :-)
这是我目前所达到的:
// inside my if (entity != null) statement
List<Cookie> cookies = postClient.getCookieStore().getCookies();
String result = cookies.get(1).toString();
return result;
当我登录后,CookieList id 1 包含一个值,否则该值是标准的。所以现在我知道值(value)的差异,但我该如何继续?
最佳答案
我认为 Android 附带 Apache HttpClient 4.0。
可以查看Chapter 3. HTTP state management来自 HttpClient 教程的主题。
你也可以在 SO 上引用类似的问题:
Android project using httpclient --> http.client (apache), post/get method
How do I manage cookies with HttpClient in Android and/or Java?
关于java - 从 HTTP 请求设置 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3715337/