2011-07-19 18 views
0

このメソッドは、私が制御するWebサービスを消費するために使用されます。 Webサービスは、ユーザーがログインしたままにするためのCookieを設定します。Webサービスの消費とCookieの保存

これはすべてブラウザで正常に動作します。すなわち、私はログインURLを呼び出すことができ、それは私のブラウザをクッキーにし、その後のウェブサービスへのアクセスは私のクッキーを認識する。

アンドロイドでは、ログインに成功しましたが、Cookieが設定されていないようです。

このコードがクッキーデータをどこに出力するかを確認することができます。これは、ログインスクリプトにヒットしたときにクッキーを表示しますが、この関数への後続の呼び出しではクッキーを認識しません。

はここに私が使用しているコードですが、私は他の例の誰かが投稿から始まっ:あなたのHttpClientとは、cookiestoreがてgetResponseに対してローカルであるためであるかもしれない

private JSONObject getResponse(String func, List<NameValuePair> args) throws Exception { 

    HttpClient httpclient = new DefaultHttpClient(); 
    try { 
     // Create a local instance of cookie store 
     CookieStore cookieStore = new BasicCookieStore(); 

     // Create local HTTP context 
     HttpContext localContext = new BasicHttpContext(); 
     // Bind custom cookie store to the local context 
     localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); 

     HttpPost put= new HttpPost("http://example.com/api/" + func); 
     if (args != null) { 
      put.setEntity(new UrlEncodedFormEntity(args)); 
     } 

     System.out.println("executing request " + put.getURI()); 

     // Pass local context as a parameter 
     HttpResponse response = httpclient.execute(put, localContext); 
     HttpEntity entity = response.getEntity(); 

     System.out.println("----------------------------------------"); 
     System.out.println(response.getStatusLine()); 
     if (entity != null) { 
      System.out.println("Response content length: " + entity.getContentLength()); 
     } 
     List<Cookie> cookies = cookieStore.getCookies(); 
     for (int i = 0; i < cookies.size(); i++) { 
      System.out.println("Local cookie: " + cookies.get(i)); 
     } 

     // Consume response content 
     //EntityUtils.consume(entity); 
     System.out.println("----------------------------------------"); 

     InputStream instream = entity.getContent(); 
     String result = convertStreamToString(instream); 
     instream.close(); 
     entity.consumeContent(); 

     System.out.println("JSON Output: " + result); 

     return new JSONObject(result); 

    } finally { 
     // When HttpClient instance is no longer needed, 
     // shut down the connection manager to ensure 
     // immediate deallocation of all system resources 
     httpclient.getConnectionManager().shutdown(); 
    } 
} 

答えて

3

を。それらをグローバルにして、後続の呼び出しに耐えられるようにしてください。

2

あなたがアクセスしようとしているURLにコンテンツをロックし、手動で使用して行うことができます次に来るの呼び出し、ためにクッキーを設定する必要があります呼び出し:私は別の答えについて書かれている

HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
httpURLConnection.setInstanceFollowRedirects(false); 

httpURLConnection.setRequestProperty("Host", domainOfYourCookie); 
httpURLConnection.setRequestProperty("Cookie", valueOfYourCookie); 

をこのトピックはhereです。

関連する問題