1

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();
user2699406
  • 85
  • 3
  • 8

2 Answers2

1

Try this :

CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance(); 
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(url,value);
cookieSyncManager.sync();
user3535747
  • 253
  • 1
  • 2
  • 7
0

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.

user2699406
  • 85
  • 3
  • 8
  • If you want to create a cookie store from a string (example if you persist cookies or you don't use httpClient as a singleton) have a look at this answer http://stackoverflow.com/a/15924948/1714030 – Daniel Backman Aug 08 '14 at 22:31