質問

Hi i'm using seperate instance of HttpClient and instance of HttpResponce to make multiple http calls and get the response from a server. The problem is that i can not store cookies, and every time i make a request after login, returns "Authentication error: Unable to respond to any of these challenges". how can i store the cookies for my usecase? Here's the code:

public class MyHttpClient {

private DefaultHttpClient httpClient = new DefaultHttpClient();

    private CookieStore cookieStore = new BasicCookieStore();
    BasicHttpContext localContext = new BasicHttpContext();


 public MyHttpResponse get(String url) throws IOException{
          cookieStore = httpClient.getCookieStore();
          localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
      HttpGet httpGet = new HttpGet(url);
      return new MyHttpResponse(httpClient.execute(httpGet, localContext));

}

public MyhttpResponse post(String url, Arraylist<String> params ) throws IOException{
     cookieStore = httpClient.getCookieStore();
     localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
     HttpPost httpPost = new HttpPost(url);
     /* put params */
 return new MyHttpResponse(httpClient.execute(httpPost, localContext));

}

And MyResponse get the response body:

   if(response.getEntity() != null){
        InputStream lineStream = response.getEntity().getContent();
役に立ちましたか?

解決 2

I made it to work after make my httpClient as Singleton. I don't know if this is the best solution to keep the session across the app, but it is working.

他のヒント

Try this :

CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance(); 
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(url,value);
cookieSyncManager.sync();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top