问题描述
- android studio 获取cookie
-
最近一段时间开始使用android stuido 公司接口一直都有要获取cookie 进行登录 。然而
/*
* 获取cookie值
*/
public void getCookie(Context mContext) {DefaultHttpClient defaultHttpClient = (DefaultHttpClient) getHttpClient(); List<Cookie> cookies = defaultHttpClient.getCookieStore().getCookies(); for (int i = 0; i < cookies.size(); i++) { if (cookies.get(i).getName().equals("token")) { String cookie = cookies.get(i).getValue(); ACacheConst.cookie = cookie; ACache.get(mContext).put(ACacheConst.COOKIE, cookie); System.out.println("cookie---------------" + cookie); } } } 这段代码 在eclipse 上是完全没有问题的 但是在studio 就不行啊 后面找了下原因是 6.0 把HttpClient相关的类去掉了 要添加依赖库 于是 我再studio 添加了下 useLibrary 'org.apache.http.legacy' 就没问题了 但是问题来了 上面那段代码 在studio 上面还是获取不到cookie 我使用的是 retrofit 网络请求库 有没大神知道如何解决的 急 谢谢
解决方案
你用 retrofit 的话
http://stackoverflow.com/questions/21530307/set-custom-cookie-in-retrofit
I had similar situation in my app. This solution works for me to retrieve cookies using Retrofit. MyCookieManager.java
import java.io.IOException;
import java.net.CookieManager;
import java.net.URI;
import java.util.List;
import java.util.Map;
class MyCookieManager extends CookieManager {
@Override
public void put(URI uri, Map<String, List<String>> stringListMap) throws IOException {
super.put(uri, stringListMap);
if (stringListMap != null && stringListMap.get("Set-Cookie") != null)
for (String string : stringListMap.get("Set-Cookie")) {
if (string.contains("userid")) {
//save your cookie here
}
}
}
}
Here is how to set your cookie for future requests using RequestInterceptor:
MyCookieManager myCookieManager = new MyCookieManager();
CookieHandler.setDefault(myCookieManager);
private static final RestAdapter REST_ADAPTER = new RestAdapter.Builder()
.setEndpoint(API_URL)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade requestFacade) {
String userId = ;//get your saved userid here
if (userId != null)
requestFacade.addHeader("Cookie", userId);
}
})
.build();
https://github.com/square/retrofit/issues/503
时间: 2024-10-30 11:09:12