1

我需要向服务器发出两个请求。在第一个请求中,我发送参数 userID = 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);}
    }
}
4

1 回答 1

1

在第二次通话中你不做

httpclient.execute(httppost, localContext);
于 2013-05-17T12:14:47.453 回答