我的应用程序执行 HTTP POSTS,通常该应用程序可以工作,但我遇到了 cookie 问题。我的代码似乎通过 HttpClient 变量并输出了 cookie,但 POST 的结果显示我的应用程序(作为客户端)没有记住任何内容。(当我在我的电脑上使用网络浏览器时,它工作正常,cookie 会记住我的名字)此外,如果重新启动应用程序,cookie 会消失(......但首先要做的事)
这是我的代码:
static DefaultHttpClient httpclient;
static HttpPost httppost;
static CookieStore cookiestore;
new Thread(new Runnable() {
public void run() {
String URI_FOR_DOMAIN="http://chatbot.t.com/cgi-bin/elbot.cgi";
httppost = new HttpPost(URI_FOR_DOMAIN);
try {
HttpResponse resp = httpclient.execute(httppost);
} catch (IOException e) {
e.printStackTrace();
}
cookiestore = ((DefaultHttpClient) httpclient).getCookieStore();
List<Cookie> list = cookiestore.getCookies();
app.logy("COOKIE STORE 1: " + cookiestore.toString());
app.logy("COOKIE LIST 1: "+list.toString());
for (int i=0;i<list.size();i++) {
Cookie cookie = list.get(i);
app.logy("COOKIE "+i+": "+cookie.toString());
}
HttpContext context = new BasicHttpContext();
context.setAttribute( ClientContext.COOKIE_STORE, cookiestore);
httppost = new HttpPost(url);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<>(2);
nameValuePairs.add(new BasicNameValuePair("ENTRY", userInput));
nameValuePairs.add(new BasicNameValuePair("IDENT", userIDENT));
nameValuePairs.add(new BasicNameValuePair("USERLOGID", userLOGID));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
app.logy("COOKIE STORE 2: "+cookiestore.toString());
app.logy("COOKIE CONTEXT: " + context.toString());
HttpResponse response = httpclient.execute(httppost, context);
cookiestore = ((DefaultHttpClient) httpclient).getCookieStore();
List<Cookie> list2 = cookiestore.getCookies();
app.logy("COOKIE STORE 2: " + cookiestore.toString());
app.logy("COOKIE LIST 2: "+list2.toString());
for (int i=0;i<list2.size();i++) {
Cookie cookie = list2.get(i);
app.logy("COOKIE2 i="+i+": "+cookie.toString());
}
HttpEntity entity = response.getEntity();
}
}
app.logy(sb.toString());
}
catch (IOException e) { e.printStackTrace(); }
catch (Exception e) { e.printStackTrace(); }
} catch (ClientProtocolException e) {
app.logy("HttpPOST (ClientProtocol) error: "+e);
} catch (IOException e) {
app.logy("HttpPOST (I/O) error: "+e);
}
}
}).start();
这是上述代码的 Logcats 中反映的值。cookie 似乎在那里,但 HttpResponse response = httpclient.execute(httppost, context); 似乎忽略了他们。
COOKIE STORE 2: [[version: 0][name: cookie_user_name][value: Albert][domain: elbot-e.artificial-solutions.com][path: /][expiry: Thu Oct 08 22:26:54 GMT+02:00 2015]]
COOKIE LIST 2: [[version: 0][name: cookie_user_name][value: Albert][domain: elbot-e.artificial-solutions.com][path: /][expiry: Thu Oct 08 22:26:54 GMT+02:00 2015]]
COOKIE2 i=0: [version: 0][name: cookie_user_name][value: Albert][domain: elbot-e.artificial-solutions.com][path: /][expiry: Thu Oct 08 22:26:54 GMT+02:00 2015]