我需要两个请求到服务器。 在第一请求我发送参数的用户ID = 1和服务器返回一个cookie _session_ID。 现在,我不带参数发送第二请求,其结果应该是一样的第一次。 但是,该cookie不会被发送。 为什么?
这是我的代码:
public class Server
{
static HttpClient httpclient;
static HttpPost httppost;
static String JsonString;
static HttpResponse response;
static List <NameValuePair> nameValuePairs;
static CookieStore cookieStore;
static HttpContext localContext;
static List<Cookie> cookies;
static int cookieSize;
public static void Clear()
{
try
{
cookieStore = new BasicCookieStore();
localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://mobile-app-storage.herokuapp.com/test");
nameValuePairs = new ArrayList <NameValuePair> (2);
nameValuePairs.add(new BasicNameValuePair("userID", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost, localContext);
JsonString = ReadFromServer(response.getEntity().getContent());
Log.e("Request", "1");
cookies = cookieStore.getCookies();
cookieSize = cookies.size();
for (int i = 0; i < cookieSize; i++)
{
Log.v("Cookie "+ i, "name: "+cookies.get(i).toString());
}
// Second request without userID. Must be same result as first
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://mobile-app-storage.herokuapp.com/test");
nameValuePairs.clear();
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
JsonString = ReadFromServer(response.getEntity().getContent());
Log.e("Request", "2");
cookies = cookieStore.getCookies();
cookieSize = cookies.size();
for (int i = 0; i < cookieSize; i++)
{
Log.v("Cookie "+ i, "name: "+cookies.get(i).toString());
}
}
catch (Throwable e) {Log_.Error(e);}
}
}