您好我正在使用HttpClient的单独实例和HttpResponce实例进行多次http调用并从服务器获取响应。问题是我无法存储cookie,每次登录后发出请求都会返回“身份验证错误:无法响应任何这些挑战”。我如何为我的用例存储cookie?这是代码:
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));
}
MyResponse获得回复正文:
if(response.getEntity() != null){
InputStream lineStream = response.getEntity().getContent();
答案 0 :(得分:1)
试试这个:
CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(url,value);
cookieSyncManager.sync();
答案 1 :(得分:0)
在将我的httpClient设为Singleton后,我开始工作了。我不知道这是否是在整个应用程序中保持会话的最佳解决方案,但它确实有效。