繁体   English   中英

httpClient无法在我的android应用中保留具有许多异步请求的cookie

[英]httpClient can not retain cookie with many async request in my android app

我正在使用HttpClient和ClientConnectionManager来管理andorid中的http请求。 以下MyHttp类是唯一处理所有http方法的类。

但是有许多异步http请求,我发现httpClient无法发送正确的cookie。 例如,在我的应用程序中,在应用程序启动时有五个请求。但是有两种类型的cookie从服务器发送和发送到服务器。 在服务器端。 你能给我一点吗?

PS:我有另一个Web项目和ios项目使用相同的api服务器,它们在cookie处理上都是正确的。

MyHttp是我的BaseActivity中的实例化,它扩展了Activtiy

public class MyHttp {
    public static HttpClient  httpClient;
    public static HttpContext localContext;

    public MyHttp() {

    }

    public String getHttp(String url) throws Exception {
        String result = "";
        HttpGet getMethod = new HttpGet(url);
        getMethod.addHeader("Content-Type","application/json");
        HttpResponse response = httpClient.execute(getMethod,localContext);

        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            result = EntityUtils.toString(response.getEntity(), "utf-8");
        }    
        return result;
    }



    public static synchronized HttpClient getHttpClient() {
        /**cookie*/
        CookieStore cookieStore = new BasicCookieStore();
        // Create local HTTP context
        localContext = new BasicHttpContext();
        // Bind custom cookie store to the local context
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        if (null == httpClient) {
            // 初始化工作
            HttpParams params = new BasicHttpParams();

            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

            // 设置http https支持
            SchemeRegistry schReg = new SchemeRegistry();
            schReg.register(new Scheme("http", PlainSocketFactory
                    .getSocketFactory(), 80));
            schReg.register(new Scheme("https", sf, 443));

            ClientConnectionManager conManager = new ThreadSafeClientConnManager(
                    params, schReg);

            httpClient = new DefaultHttpClient(conManager, params);
        }
        return httpClient;
    }

}

在您的getHttpClient()方法中,您将在每次调用时创建BasicCookieStoreBasicHttpContext的新实例。 这将导致在不同的时间使用不同的cookie存储,并可能导致cookie丢失。

我建议您仅实例化localContext一次,并在每次请求时重用此实例。

PS我真的建议你不要使用HttpClient Google不再支持它,您也不应该花时间在上面。 最好使用HttpUrlConnection或一些可用的HTTP通信框架-Volley,OkHttp,Retrofit等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM