我通过OKHttpClient帖子以用户身份登录,我想与webview共享cookie。OkHTTPClient将Cookie传递给Webview
回答
随着OkHttp 3.0,你可以使用类似于通过使使用WebKit的cookie存储一个WebkitCookieManagerProxy与HttpURLConnection的共享方法。改编自Pass cookies from HttpURLConnection (java.net.CookieManager) to WebView (android.webkit.CookieManager)。
public class WebkitCookieManagerProxy extends CookieManager implements CookieJar {
private android.webkit.CookieManager webkitCookieManager;
private static final String TAG = WebkitCookieManagerProxy.class.getSimpleName();
public WebkitCookieManagerProxy() {
this(null, null);
}
WebkitCookieManagerProxy(CookieStore store, CookiePolicy cookiePolicy) {
super(null, cookiePolicy);
this.webkitCookieManager = android.webkit.CookieManager.getInstance();
}
@Override
public void put(URI uri, Map<String, List<String>> responseHeaders)
throws IOException {
// make sure our args are valid
if ((uri == null) || (responseHeaders == null))
return;
// save our url once
String url = uri.toString();
// go over the headers
for (String headerKey : responseHeaders.keySet()) {
// ignore headers which aren't cookie related
if ((headerKey == null)
|| !(headerKey.equalsIgnoreCase("Set-Cookie2") || headerKey
.equalsIgnoreCase("Set-Cookie")))
continue;
// process each of the headers
for (String headerValue : responseHeaders.get(headerKey)) {
webkitCookieManager.setCookie(url, headerValue);
}
}
}
@Override
public Map<String, List<String>> get(URI uri,
Map<String, List<String>> requestHeaders) throws IOException {
// make sure our args are valid
if ((uri == null) || (requestHeaders == null))
throw new IllegalArgumentException("Argument is null");
// save our url once
String url = uri.toString();
// prepare our response
Map<String, List<String>> res = new java.util.HashMap<String, List<String>>();
// get the cookie
String cookie = webkitCookieManager.getCookie(url);
// return it
if (cookie != null) {
res.put("Cookie", Arrays.asList(cookie));
}
return res;
}
@Override
public CookieStore getCookieStore() {
// we don't want anyone to work with this cookie store directly
throw new UnsupportedOperationException();
}
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
HashMap<String, List<String>> generatedResponseHeaders = new HashMap<>();
ArrayList<String> cookiesList = new ArrayList<>();
for(Cookie c: cookies) {
// toString correctly generates a normal cookie string
cookiesList.add(c.toString());
}
generatedResponseHeaders.put("Set-Cookie", cookiesList);
try {
put(url.uri(), generatedResponseHeaders);
} catch (IOException e) {
Log.e(TAG, "Error adding cookies through okhttp", e);
}
}
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
ArrayList<Cookie> cookieArrayList = new ArrayList<>();
try {
Map<String, List<String>> cookieList = get(url.uri(), new HashMap<String, List<String>>());
// Format here looks like: "Cookie":["cookie1=val1;cookie2=val2;"]
for (List<String> ls : cookieList.values()) {
for (String s: ls) {
String[] cookies = s.split(";");
for (String cookie : cookies) {
Cookie c = Cookie.parse(url, cookie);
cookieArrayList.add(c);
}
}
}
} catch (IOException e) {
Log.e(TAG, "error making cookie!", e);
}
return cookieArrayList;
}
然后在构建OkHttpClient时添加代理的实例作为cookieJar。
client = new OkHttpClient.Builder().cookieJar(proxy).build();
这很好用!谢谢! –
如何将以上内容与PersistentCookieStore一起使用https://stackoverflow.com/a/34886860/3286489? – Elye
此链接帮助,但我不得不改变我的用例的几件事情:http://artemzin.com/blog/use-okhttp-to-load-resources-for-webview/
下面的代码工作:
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
//enable javascript...
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progress.dismiss();
}
@SuppressWarnings("deprecation")
@Override
public WebResourceResponse shouldInterceptRequest(@NonNull WebView view, @NonNull String url) {
return handleRequestViaOkHttp(url);
}
});
webView.loadUrl("MY_URL.COM");
然后,做了基本身份验证+代码处理拦截使用OkHTTPClient的webview请求。
@NonNull
private WebResourceResponse handleRequestViaOkHttp(@NonNull String url) {
try {
OkHttpClient client = new OkHttpClient();
client.setAuthenticator(new Authenticator() {
//for basic authorization...
@Override
public Request authenticate(Proxy proxy, com.squareup.okhttp.Response response) throws IOException {
String credential = Credentials.basic(CommonResource.HEADER_USERNAME, CommonResource.HEADER_PASSWORD);
return response.request().newBuilder().header("Authorization", credential).build();
}
@Override
public Request authenticateProxy(Proxy proxy, com.squareup.okhttp.Response response) throws IOException {
return null;
}
});
final Call call = client.newCall(new Request.Builder()
.url(url)
.build()
);
final Response response = call.execute();
return new WebResourceResponse("text/html", "UTF-8", response.body().byteStream());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
这将是非常酷是有人想追加到代码,以允许在现有的表格上发布信息:) –
这不是一个好主意,请参阅https://artemzin.com/blog/android-webview-io/。 拦截webview网络请求会使它们在chrome 47之前顺序执行,而5.0之前的Android客户端不会更新其web视图。 – RyanCheu
- 1. 将Cookie传递给Android WebView
- 2. 将Cookie传递给Image.GetInstance
- 3. 将cookie传递给httpwebrequest
- 4. 将Cookie传递给Net :: HTTP.start
- 5. Webview - 将值从javascript传递给java
- 6. 将URL从WebView传递给ShareActionProvider?
- 7. 将登录信息传递给webview
- 8. 如何将此凭据传递给WebView
- 9. 将Facebook SDK会话传递给webview
- 10. Xamarin - 从HttpClient将会话传递给WebView
- 11. 如何将javascript值传递给cookie
- 12. Android - 将Cookie传递给Opera Mobile
- 13. 将cookie传递给JSON请求
- 14. 如何将会话cookie传递给Uploadify?
- 15. 如何将xsrf cookie传递给主机?
- 16. 将cookie传递给我的浏览器
- 17. 将现有cookie传递给Web服务
- 18. 如何将cookie从jquery传递给PHP?
- 19. 如何将cookie传递给NSUrlSession?
- 20. DefaultHttpClient post获取会话cookie并传递给WebView android
- 21. 以Cookie格式获取Cookie并将其传递给CookieStore?
- 22. 我可以将Javascript对象传递给Android WebView吗?
- 23. Android将触摸事件传递给WebView的内容
- 24. 将活动值传递给Android webview的Javascript方法
- 25. 如何将Java中的值传递给Javascript嵌入Android WebView
- 26. 如何将html字符串传递给android上的webview
- 27. Android Webview将标题数据传递给Google Analytics
- 28. 将Android Activity中的值数组传递给WebView中的JavaScript
- 29. 如何将html字符串传递给另一个活动webView
- 30. 如何将JSON传递给Android webview中的AngularJS?
和你的问题是?如果是“我该怎么做?”,那太宽泛了。如果它是“我在哪里找到一个教程来做到这一点?”,那也将被关闭。你有特定的问题吗? – njzk2
尽管这里的简短描述问题很明显,但是由此重复:http://stackoverflow.com/questions/7610790/add-custom-headers-to-webview-resource-requests-android – Than