HttpClientへのCookie設定

5,778 views
Skip to first unread message

ayako horiuchi

unread,
Feb 14, 2011, 6:47:39 AM2/14/11
to android-...@googlegroups.com
こんばんは。堀内といいます。
 
WebViewでサーバと通信した際に作成したCookieを、HttpClientでの通信でも使用したいと考えています。
WebViewからCookieを取得するのはできたのですが、HttpClientに設定する部分がうまくいってないようです。
 
サンプルを探せなくて、関数の整合性だけでソース書きました。
しかも、JavaでCookie使うの初めてなので、とんでもない勘違いしている可能性ありです。
書くのだけでいっぱいいっぱいで、どこが変なのかさっぱり状態なので、ご協力お願いします。
 
 
1.WebViewのCookieの値を取得
----------
CookieManager cookie = CookieManager.getInstance();
String cookiestr = cookie.getCookie(url);
----------
cookiestrは"hoge=xxxxxxxxxx; hoge=xxxxxxxxxx;"のような感じです
PHPでsetcookie("hoge"、 "xxxxxxxxxx");した値がちゃんと入ってるので正しいはず
 
2.HttpClientにCookieの値を設定
Cookieの値はHashMap<String, String>に格納済みで
BasicClientCookieにHashMapの値を入れてます
----------
URI uri = new URI(path);
DefaultHttpClient client = new DefaultHttpClient();
client.getParams().setParameter("http.connection.timeout", new Integer(15000));
// Cookieの設定
if (cookie != null) {
  CookieStore store = client.getCookieStore();
  Iterator<String> ite = cookie.keySet().iterator();
  while (ite.hasNext()) {
    String key = ite.next();
    store.addCookie(new BasicClientCookie(key, cookie.get(key)));
  }
}
 
<中略>
 
// HTTP接続
HttpResponse response = client.execute(method);
int status = response.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK) {
  // 失敗
  return null;
}
 
// レスポンスデータ取得
return response.getEntity().getContent();
----------
 
3.HttpClientの通信先でCookieの値を取得
2で設定したCookieの値がほしいけど取れない
 
 
気づいたことありましたら、ご教授ください。
よろしくお願いします。

ayako horiuchi

unread,
Feb 14, 2011, 10:09:58 PM2/14/11
to android-...@googlegroups.com
堀内です。
自己解決したのでご報告に。
 
WebView側でgetCookieした文字列を「そのまま」
HttpClient側のHttpPostでsetHeader("Cookie", val)
してあげたら、通りました。
ちょっとがっくりしました。
一応修正ソースを載せておきます。
 
 
1.WebViewのCookieの値を取得(変更なし)

----------
CookieManager cookie = CookieManager.getInstance();
String cookiestr = cookie.getCookie(url);
----------
 
2.HttpClientにCookieの値を設定

----------
URI uri = new URI(path);
DefaultHttpClient client = new DefaultHttpClient();
client.getParams().setParameter("http.connection.timeout", new Integer(15000));
 
HttpPost method = new HttpPost(uri);
// Cookieの設定
method.setHeader("Cookie", cookiestr);
// HTTP接続
HttpResponse response = client.execute(method);
int status = response.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK) {
    // 失敗
    return null;
}
 
// レスポンスデータ取得
return response.getEntity().getContent();
----------

 
2011年2月14日20:47 ayako horiuchi <hori...@gmail.com>:
Reply all
Reply to author
Forward
0 new messages