如何在Android中的POST请求后获取cookie?

时间:2014-01-18 15:31:55

标签: android cookies android-asynctask

这是我的类的doInBackground方法,它扩展了AsyncTask以执行POST请求

@Override
protected Integer doInBackground(String... arg0) {

    HttpClient client = new DefaultHttpClient();

    Log.d("HTTP", "URL:" + arg0[0]);
    HttpPost post = new HttpPost(arg0[0]);

    try {
        // Add your data
        post.setEntity(new UrlEncodedFormEntity(login)); 

        // Execute HTTP Post Request
        HttpResponse response = client.execute(post);

        //to Log the response headers
        Header[] headers = response.getAllHeaders();
        for (int i=0; i < headers.length; i++) {
            Header h = headers[i];
            Log.i("Header","Header names: "+h.getName());
            Log.i("Header", "Header Value: "+h.getValue());
        }

        int respCode = response.getStatusLine().getStatusCode();
        Log.d("HTTP", "POST:"+arg0[0]+" Risposta Server dopo invio: "+respCode);

        return respCode;
    } catch (IOException e) {
        // Gestire nel codice finale
        e.printStackTrace();
    }

这是logcat:

  
    

01-18 14:44:26.532:I / Header(591):标题名称:日期

  
     

01-18 14:44:26.543:I / Header(591):Header Value:Sat,2014年1月18日14:44:21 GMT

     

01-18 14:44:26.543:I / Header(591):标题名称:服务器

     

01-18 14:44:26.543:I / Header(591):标题值:Apache

     

01-18 14:44:26.543:I / Header(591):标题名称:Set-Cookie

     

01-18 14:44:26.543:I / Header(591):标题值:session_id = 29ae962bcc7cbb648c4b2e35b2a7b4f6;路径= /;域= .forumcommunity.net;仅Http

     

01-18 14:44:26.543:I / Header(591):标题名称:X-Frame-Options

     

01-18 14:44:26.553:I / Header(591):标题值:DENY

     

01-18 14:44:26.553:I / Header(591):标题名称:Set-Cookie

     

01-18 14:44:26.553:I / Header(591):标题值:member_id = 8712154;到期=太阳,   2015年1月18日14:44:21 GMT;路径= /;域= .forumcommunity.net;仅Http

     

01-18 14:44:26.553:I / Header(591):标题名称:Set-Cookie

     

01-18 14:44:26.572:I / Header(591):标题值:pass_hash = 83e8e0213aa10058b2d014bc0331598d6076bd23f145d03b6ee8a31b2eb25e96; expires = Sun,18-Jan-2015 14:44:21 GMT;路径= /;域= .forumcommunity.net;仅Http

     

01-18 14:44:26.572:I / Header(591):标题名称:变化

     

01-18 14:44:26.572:I / Header(591):标题值:接受编码

     

01-18 14:44:26.572:I / Header(591):标题名称:P3P

     

01-18 14:44:26.582:I / Header(591):标题值:CP =&#34; NOI ADM DEV COM TO STP&#34;

     

01-18 14:44:26.582:I / Header(591):标题名称:连接

     

01-18 14:44:26.582:I / Header(591):标题值:关闭

     

01-18 14:44:26.602:I / Header(591):标题名称:转移编码

     

01-18 14:44:26.602:I / Header(591):标题值:分块

     

01-18 14:44:26.602:I / Header(591):标题名称:Content-Type

     

01-18 14:44:26.602:I / Header(591):标题值:text / html;字符集=窗口1252

如何才能获取Set-Cookie标头并将其解析为Cookie列表?

1 个答案:

答案 0 :(得分:0)

查看HTTP请求后访问cookie的示例: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/httpclient/src/examples/org/apache/http/examples/client/ClientCustomContext.java

client.execute()之后使用此代码获取Cookie:

List<Cookie> cookies = cookieStore.getCookies();