我正在开发一个Android应用程序,它将带有用户名和密码的发布请求发送到服务器,然后我成功地获得了正确的响应。但是,当我在登录后尝试单击发送另一个帖子请求的按钮时,我从服务器收到一条消息,说我还没有登录。我知道这与存储cookie有关,有人可以帮我解决这样做?这是html客户端代码:
public class SimpleHttpClient {
private static HttpClient mHttpClient;
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
答案 0 :(得分:1)
我前段时间遇到过同样的问题。
您可以在CookieStore中序列化Cookie并在登录时将其保存在某处。
httpclient.execute(//login);
CookieStore cookieStore = httpclient.getCookieStore();
saveCookieData(cookieStore);
在发出帖子请求之前,请对其进行反序列化,然后将其设置为http客户端。
httpclient.setCookieStore(retrieveCookieStore());