我使用HttpRequest获得正确的登录工作。它在我的吐司中打印登录页面的正确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包含一个值,否则该值是标准值。所以现在我知道价值的差异,但我怎么能继续?
答案 0 :(得分:2)
我认为Android附带Apache HttpClient 4.0。
您可以查看HttpClient教程中的Chapter 3. HTTP state management主题。
你也可以在SO上提到类似的问题:
Android project using httpclient --> http.client (apache), post/get method
How do I manage cookies with HttpClient in Android and/or Java?