【问题标题】:Http cookie store in AndroidAndroid 中的 Http cookie 存储
【发布时间】:2011-12-29 07:39:46
【问题描述】:

我正在为具有授权的站点开发 Android 客户端。我有一个post方法。示例我的代码:

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);      
}

如何保存 cookie?

【问题讨论】:

    标签: java android cookies httpclient


    【解决方案1】:

    你从HttpResponse response获取你的cookies:

    Header[] mCookies = response.getHeaders("cookie");
    

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

    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);
    

    【讨论】:

    • 这一行错误Cookie cookie = BasicClientCookie("name", "value");。可以使用Cookie cookie = new BasicClientCookie("name", "value");?
    • 是的,我的错误,忘记了new关键字。
    • String mCookies[] 必须是 Header[] mCookies 否则会是类型转换问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 2011-05-04
    • 2013-05-14
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多