如何okhttp把cookies传到ios webview cookies

| 时间排序
谢邀。&br&&br&不知为啥最近总被各种各样的人拉去回答各种各样webview的问题,难道我被发现了?嘿嘿嘿~&br&&br&正经的,ios中的uiwebview停止加载,安卓上是webview.stopLoadding(),ios应该类同。&br&&img src=&/6e948a587c31d96bab2b28e58d56a621_b.png& data-rawwidth=&451& data-rawheight=&510& class=&origin_image zh-lightbox-thumb& width=&451& data-original=&/6e948a587c31d96bab2b28e58d56a621_r.png&&
谢邀。不知为啥最近总被各种各样的人拉去回答各种各样webview的问题,难道我被发现了?嘿嘿嘿~正经的,ios中的uiwebview停止加载,安卓上是webview.stopLoadding(),ios应该类同。
web view 有缓存啊&br&//设置 缓存模式&br&webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); &br&// 开启 DOM storage API 功能 &br&
webView.getSettings().setDomStorageEnabled(true); &br&这样你就可以在返回前一个页面的时候不刷新了
web view 有缓存啊//设置 缓存模式webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // 开启 DOM storage API 功能
webView.getSettings().setDomStorageEnabled(true); 这样你就可以在返回前一个页面的时候不刷新了
webView.canGoback();&br&webView.goBack();&br&不知道能否符合你的需求
webView.canGoback();webView.goBack();不知道能否符合你的需求
你好,请问你这个问题解决了吗?如何解决的呢?能分享一下吗?
你好,请问你这个问题解决了吗?如何解决的呢?能分享一下吗?
在魅族m1 metal、乐视等手机上,app中第一次使用webview时会黑屏崩溃,&br&No implementation found for java.lang.String com.android.org.chromium.base.library_loader.LibraryLoader.nativeGetVersionNumber() (tried Java_com_android_org_chromium_base_library_1loader_LibraryLoader_nativeGetVersionNumber and Java_com_android_org_chromium_base_library_1loader_LibraryLoader_nativeGetVersionNumber__)&br&等它崩溃后再启动,就一切正常了。&br&郁闷的是,专门写个webview的demo,又特么一切正常。目前无解。
在魅族m1 metal、乐视等手机上,app中第一次使用webview时会黑屏崩溃,No implementation found for java.lang.String com.android.org.chromium.base.library_loader.LibraryLoader.nativeGetVersionNumber() (tried Java_com_android_org_chromium_base_l…
我遇到的情况是navigator.geolocation.getCurrentPosition()这个方法在小米手机work,在Samsung和moto fail。&br&解决办法是:打开vpn,打开googlemap定位,再打开webview work!&br&发出来或许对其他人有用。
我遇到的情况是navigator.geolocation.getCurrentPosition()这个方法在小米手机work,在Samsung和moto fail。解决办法是:打开vpn,打开googlemap定位,再打开webview work!发出来或许对其他人有用。
github上WebViewJavascriptBridge,附送一个之前看到的文章,&a href=&///?target=http%3A///webview-javascript-bridge/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&UIWebView与JS的深度交互&i class=&icon-external&&&/i&&/a&&br&最后说明一点,用通讯桥做大量交互,在模拟器上都能感受到明显的延迟。
github上WebViewJavascriptBridge,附送一个之前看到的文章,最后说明一点,用通讯桥做大量交互,在模拟器上都能感受到明显的延迟。
github上,js-bridge.
github上,js-bridge.
先打开界面然后关闭网络再刷新一次就能辨别出来是原生还是web了,是web的话就会显示网页无法访问之类的,原生的那些界面控件还在。
先打开界面然后关闭网络再刷新一次就能辨别出来是原生还是web了,是web的话就会显示网页无法访问之类的,原生的那些界面控件还在。
会回调啊,你注意一下自己的清单文件设置版本不要到21,不然会有问题,我的 &uses-sdk&br&
android:minSdkVersion=&9&&br&
android:targetSdkVersion=&19& /&
会回调啊,你注意一下自己的清单文件设置版本不要到21,不然会有问题,我的 &uses-sdk android:minSdkVersion="9" android:targetSdkVersion="19" /&
已有帐号?
社交帐号登录
无法登录?
社交帐号登录用Okhttp框架登录之后的Cookie设置到webView无效?
如题,我自己的安卓应用中,使用到的请求框架是Okhttp,登录是用该框架请求的,然后有将cookie保存起来,应用中有页面使用webview,然后需要将cookie设置到webview中去。现在的情况是网上找的各种方法都有试过,但是一直无效,webview加载url的时候依然会跳转到网页端的登录页面。求各路大神解决。
安卓WebView用的是谷歌的浏览器内核,可以看成是内嵌进去的chrome,由于谷歌的安全机制,安卓WebView的cookie在本地是访问不了的,我们项目的hybrid,本地文件是放在asset文件夹里,所以读写不了cookie,不知道你的是不是
已有帐号?
社交帐号登录
无法登录?
社交帐号登录17585人阅读
Android(56)
Android提供了WebView控件展示web页面的能力,还可通过WebViewClient类辅助WebView处理各种通知、请求。
核心代码:
mWebView = (WebView) findViewById(R.id.WebView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(&&);
Activity文件
package com.app.
import android.app.A
import android.os.B
import android.view.KeyE
import android.webkit.WebV
import android.webkit.WebViewC
import android.widget.T
* WebView控件
* @author 402-9
public class WebViewTest extends Activity{
private WebView webV
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);//设置使用够执行JS脚本
webView.getSettings().setBuiltInZoomControls(true);//设置使支持缩放
webView.getSettings().setDefaultFontSize(5);
webView.loadUrl(&http://10.0.2.2:8888/csdn/&);
webView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);// 使用当前WebView处理跳转
//true表示此事件在此处被处理,不需要再广播
@Override //转向错误时的处理
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// TODO Auto-generated method stub
Toast.makeText(WebViewTest.this, &Oh no! & + description, Toast.LENGTH_SHORT).show();
@Override //默认点回退键,会退出Activity,需监听按键操作,使回退在WebView内发生
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return super.onKeyDown(keyCode, event);
XML布局文件
&?xml version=&1.0& encoding=&utf-8&?&
&LinearLayout xmlns:android=&/apk/res/android&
android:layout_width=&match_parent&
android:layout_height=&match_parent&
android:orientation=&vertical& &
android:id=&@+id/webView1&
android:layout_width=&match_parent&
android:layout_height=&match_parent& /&
&/LinearLayout&
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:419905次
积分:5680
积分:5680
排名:第2579名
原创:127篇
转载:16篇
评论:247条
文章:16篇
阅读:103734Persistent Cookie store using okhttp 2 on Android - Stack Overflow
to customize your list.
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
J it only takes a minute:
Join the Stack Overflow community to:
Ask programming questions
Answer and help your peers
Get recognized for your expertise
In my Android app, I am trying to switch from android-async-http to okhttp which supports async networking sind version 2.0. While the former ships with an implementation of a , I don't know how to implement something like this for okhttp.
In my app I have a login routine during which a get request is sent that, if successful, should set a cookie. This cookie should be appended to all subsequent network requests and should survive application restarts.
on SO, indicating that the following piece of code, if executed somewhere in the app, activates persistent cookie management and okhttp would use it:
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
However, for me it does not work. Is the CookieManager the right way to go? How could I monitor which cookies were set and stored to further debug the issue?
3,68553869
You can set your CookieStore in the OkHttp client with the following code:
OkHttpClient client = new OkHttpClient();
client.setCookieHandler(new CookieManager(
new PersistentCookieStore(getApplicationContext()),
CookiePolicy.ACCEPT_ALL));
trying to improve
in two points:
the URI should not be used if the domain and path attributes of the cookies are available.
In SerializableHttpCookie class the HttpCookie httpOnly attribute is not serialized (it does not have accessors nor mutators). My solution was to use reflection to be able to access this private attribute.
Putting the code into a custom Application's onCreate function solves the issue. It works now.
public class MyApplication extends Application {
public void onCreate() {
super.onCreate();
// enable cookies
java.net.CookieManager cookieManager = new java.net.CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
I managed to get persistent cookies with okhttp with the following CookieStore, which is partly copied from the one of android-async-http. It works with API lvl 9 and maybe fewer.
import android.content.C
import android.content.SharedP
import android.text.TextU
import android.util.L
import java.io.*;
import java.net.CookieS
import java.net.HttpC
import java.net.URI;
import java.net.URISyntaxE
import java.util.*;
import java.util.concurrent.ConcurrentHashM
* A persistent cookie store which implements the Apache HttpClient CookieStore interface.
* Cookies are stored and will persist on the user's device between application sessions since they
* are serialized and stored in SharedPreferences. Instances of this class are
* designed to be used with AsyncHttpClient#setCookieStore, but can also be used with a
* regular old apache HttpClient/HttpContext if you prefer.
public class PersistentCookieStore implements CookieStore {
private static final String LOG_TAG = "PersistentCookieStore";
private static final String COOKIE_PREFS = "CookiePrefsFile";
private static final String COOKIE_NAME_PREFIX = "cookie_";
private final HashMap&String, ConcurrentHashMap&String, HttpCookie&&
private final SharedPreferences cookieP
* Construct a persistent cookie store.
* @param context Context to attach cookie store to
public PersistentCookieStore(Context context) {
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
cookies = new HashMap&String, ConcurrentHashMap&String, HttpCookie&&();
// Load any previously stored cookies into the store
Map&String, ?& prefsMap = cookiePrefs.getAll();
for(Map.Entry&String, ?& entry : prefsMap.entrySet()) {
if (((String)entry.getValue()) != null && !((String)entry.getValue()).startsWith(COOKIE_NAME_PREFIX)) {
String[] cookieNames = TextUtils.split((String)entry.getValue(), ",");
for (String name : cookieNames) {
String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
if (encodedCookie != null) {
HttpCookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null) {
if(!cookies.containsKey(entry.getKey()))
cookies.put(entry.getKey(), new ConcurrentHashMap&String, HttpCookie&());
cookies.get(entry.getKey()).put(name, decodedCookie);
public void add(URI uri, HttpCookie cookie) {
String name = getCookieToken(uri, cookie);
// Save cookie into local store, or remove if expired
if (!cookie.hasExpired()) {
if(!cookies.containsKey(uri.getHost()))
cookies.put(uri.getHost(), new ConcurrentHashMap&String, HttpCookie&());
cookies.get(uri.getHost()).put(name, cookie);
if(cookies.containsKey(uri.toString()))
cookies.get(uri.getHost()).remove(name);
// Save cookie into persistent store
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.putString(uri.getHost(), TextUtils.join(",", cookies.get(uri.getHost()).keySet()));
prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableHttpCookie(cookie)));
protected String getCookieToken(URI uri, HttpCookie cookie) {
return cookie.getName() + cookie.getDomain();
public List&HttpCookie& get(URI uri) {
ArrayList&HttpCookie& ret = new ArrayList&HttpCookie&();
if(cookies.containsKey(uri.getHost()))
ret.addAll(cookies.get(uri.getHost()).values());
public boolean removeAll() {
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.clear();
cookies.clear();
public boolean remove(URI uri, HttpCookie cookie) {
String name = getCookieToken(uri, cookie);
if(cookies.containsKey(uri.getHost()) && cookies.get(uri.getHost()).containsKey(name)) {
cookies.get(uri.getHost()).remove(name);
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
if(cookiePrefs.contains(COOKIE_NAME_PREFIX + name)) {
prefsWriter.remove(COOKIE_NAME_PREFIX + name);
prefsWriter.putString(uri.getHost(), TextUtils.join(",", cookies.get(uri.getHost()).keySet()));
public List&HttpCookie& getCookies() {
ArrayList&HttpCookie& ret = new ArrayList&HttpCookie&();
for (String key : cookies.keySet())
ret.addAll(cookies.get(key).values());
public List&URI& getURIs() {
ArrayList&URI& ret = new ArrayList&URI&();
for (String key : cookies.keySet())
ret.add(new URI(key));
} catch (URISyntaxException e) {
e.printStackTrace();
* Serializes Cookie object into String
* @param cookie cookie to be encoded, can be null
* @return cookie encoded as String
protected String encodeCookie(SerializableHttpCookie cookie) {
if (cookie == null)
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream outputStream = new ObjectOutputStream(os);
outputStream.writeObject(cookie);
} catch (IOException e) {
Log.d(LOG_TAG, "IOException in encodeCookie", e);
return byteArrayToHexString(os.toByteArray());
* Returns cookie decoded from cookie string
* @param cookieString string of cookie as returned from http request
* @return decoded cookie or null if exception occured
protected HttpCookie decodeCookie(String cookieString) {
byte[] bytes = hexStringToByteArray(cookieString);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
HttpCookie cookie =
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
cookie = ((SerializableHttpCookie) objectInputStream.readObject()).getCookie();
} catch (IOException e) {
Log.d(LOG_TAG, "IOException in decodeCookie", e);
} catch (ClassNotFoundException e) {
Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
* Using some super basic byte array &-& hex conversions so we don't have to rely on any
* large Base64 libraries. Can be overridden if you like!
* @param bytes byte array to be converted
* @return string containing hex values
protected String byteArrayToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte element : bytes) {
int v = element & 0
if (v & 16) {
sb.append('0');
sb.append(Integer.toHexString(v));
return sb.toString().toUpperCase(Locale.US);
* Converts hex values from strings to byte arra
* @param hexString string of hex-encoded values
* @return decoded byte array
protected byte[] hexStringToByteArray(String hexString) {
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i & i += 2) {
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) && 4) + Character.digit(hexString.charAt(i + 1), 16));
The SerializableHttpCookie.java:
import java.io.IOE
import java.io.ObjectInputS
import java.io.ObjectOutputS
import java.io.S
import java.net.HttpC
public class SerializableHttpCookie implements Serializable {
private static final long serialVersionUID = 2046732L;
private transient final HttpC
private transient HttpCookie clientC
public SerializableHttpCookie(HttpCookie cookie) {
this.cookie =
public HttpCookie getCookie() {
HttpCookie bestCookie =
if (clientCookie != null) {
bestCookie = clientC
return bestC
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(cookie.getName());
out.writeObject(cookie.getValue());
out.writeObject(cookie.getComment());
out.writeObject(cookie.getCommentURL());
out.writeObject(cookie.getDomain());
out.writeLong(cookie.getMaxAge());
out.writeObject(cookie.getPath());
out.writeObject(cookie.getPortlist());
out.writeInt(cookie.getVersion());
out.writeBoolean(cookie.getSecure());
out.writeBoolean(cookie.getDiscard());
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
String name = (String) in.readObject();
String value = (String) in.readObject();
clientCookie = new HttpCookie(name, value);
clientCookie.setComment((String) in.readObject());
clientCookie.setCommentURL((String) in.readObject());
clientCookie.setDomain((String) in.readObject());
clientCookie.setMaxAge(in.readLong());
clientCookie.setPath((String) in.readObject());
clientCookie.setPortlist((String) in.readObject());
clientCookie.setVersion(in.readInt());
clientCookie.setSecure(in.readBoolean());
clientCookie.setDiscard(in.readBoolean());
3,68553869
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabled}

我要回帖

更多关于 ios webview cookies 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信