【发布时间】:2014-04-16 13:00:22
【问题描述】:
您好,我正在使用单独的 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();
【问题讨论】:
标签: android cookies httpclient