2011-11-15 4 views
2

私は認可を得てサイトのAndroidクライアントを開発しています。私はpostメソッドを持っています。例コード:AndroidのHttp Cookieストア

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

クッキーを保存するには?

答えて

13

あなたはHttpResponse responseからクッキーを取得:

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

このラインエラー 'クッキークッキー= BasicClientCookie( "名前"、 "値"); '。 'Cookie cookie = new BasicClientCookie(" name "、" value ");'? – monomi

+0

はい、私の間違いは、 'new'キーワードを忘れました。 –

+5

文字列mCookies []はヘッダー[]でなければなりませんmCookiesそれ以外の場合は型キャストの問題になります。 – Noman

関連する問題