markdowneide 2013-03-27 06:05 采纳率: 0%
浏览 3745
已采纳

在 android 中存储 Http cookie

我使用授权给网站开发一个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);      
}

如何保存 cookies?

  • 写回答

2条回答

  • nana4ever 2013-04-02 03:21
    关注

    你可以从HttpResponse response中获取 cookies

    String 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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100