Android中的Http cookie商店

mon*_*omi 2 java cookies android httpclient

我正在为该网站开发一个授权的Android客户端.我有一个帖子方法.我的代码示例:

public void run() {
    handler.sendMessage(Message.obtain(handler, HttpConnection.DID_START));
    httpClient = new DefaultHttpClient();
    HttpConnectionParams.setSoTimeout(httpClient.getParams(), 25000);
    HttpResponse response = null;
    try{            
        switch (method){
        case POST:
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeaders(headers);
            if (data != null) httpPost.setEntity(new StringEntity(data));
            response = httpClient.execute(httpPost);
            break;
        }
        processEntity(response);

    }catch(Exception e){
        handler.sendMessage(Message.obtain(handler, HttpConnection.DID_ERROR, e));

    }
    ConnectionManager.getInstanse().didComplete(this);      
}
Run Code Online (Sandbox Code Playgroud)

如何保持饼干?

Ind*_*õue 13

您可以从HttpResponse response以下位置获取Cookie :

Header[] mCookies = response.getHeaders("cookie");
Run Code Online (Sandbox Code Playgroud)

并将它们添加到您的下一个请求中:

HttpClient httpClient = new DefaultHttpClient();

//parse name/value from mCookies[0]. If you have more than one cookie, a for cycle is needed.
CookieStore cookieStore = new BasicCookieStore();
Cookie cookie = new BasicClientCookie("name", "value");
cookieStore.addCookie(cookie);

HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

HttpGet httpGet = new HttpGet("http://www.domain.com/"); 

HttpResponse response = httpClient.execute(httpGet, localContext);
Run Code Online (Sandbox Code Playgroud)

  • 字符串mCookies []必须是Header [] mCookies否则它将是一个类型转换问题. (5认同)