- Как установить cookie в клиенте Android WebView
- 3 ответа
- How I can get http-only and secure cookies on android device #76
- Comments
- cody0203 commented Aug 20, 2020 •
- marf commented Oct 27, 2020 •
- geroale commented Oct 27, 2020
- cody0203 commented Oct 29, 2020
- roeycohen commented Nov 2, 2020
- cody0203 commented Nov 3, 2020
- roeycohen commented Nov 3, 2020 •
- cody0203 commented Nov 3, 2020
- hengkx commented Nov 10, 2020
- cody0203 commented Nov 11, 2020
- hengkx commented Nov 11, 2020
- cody0203 commented Nov 11, 2020
- marf commented Nov 11, 2020 •
- cody0203 commented Nov 11, 2020 •
- marf commented Nov 11, 2020
- cody0203 commented Nov 11, 2020
- marf commented Nov 11, 2020
- cody0203 commented Nov 11, 2020 •
- rizkiandrianto commented Jan 17, 2021
- cody0203 commented Jan 18, 2021
- Проблема с файлами cookie в Android WebView
- Как загрузить страницу в WebView с куками?
Как установить cookie в клиенте Android WebView
Я хочу вызвать один конкретный URL-адрес через WebView . Страница может быть вызвана только после того, как пользователь уже вошел в систему. Я использую библиотеку AsyncHttpClient для выполнения вызова входа. После успешного входа в систему загрузка URL-адреса через WebView , похоже, не распознает правильные заголовки, например cookie. Я подозреваю, что файлы cookie неправильно синхронизируются между HttpClient и WebView’s HttpClient . Есть идеи, почему? . Вот как я использую WebView
Ценю твою помощь .
3 ответа
Ох, через несколько часов, я наконец понял, что это сработало. Во-первых, CookieSyncManager устарел в более поздних версиях Android. поскольку api 21 согласно док. Поэтому решил больше не использовать. Во-вторых, CookieManager используется для хранения файлов cookie для WebView .
Финальный код
Ключевые изменения в решении: использовать cookie.getDomain () вместо явного домена.
Попробуйте этот код, после нескольких изменений у меня работает:
Моя проблема была немного другой, но ответ от @Tixeon дал мне ключ к ее решению. Я составлял свой файл cookie и добавлял его в запрос WebView, но обнаружил, что Android переопределяет мой файл cookie и отправляет свой собственный файл cookie. Итак, прежде всего мне пришлось удалить все файлы cookie из массива, а затем создать свой собственный файл cookie. Это пример кода:
Теперь запрос содержит мой файл cookie, а не тот, который по умолчанию предоставляется Android, и мой сеанс в WebView работает. Надеюсь, это поможет кому-то другому
Источник
How I can get http-only and secure cookies on android device #76
Comments
cody0203 commented Aug 20, 2020 •
I’m current build a RN app with react-native-webview and @react-native-community/cookies. Now, i need to access all cookies in webview. With some help of @react-native-community/cookies on ios devices, i can get all of this but on android i only get non-secure/non-httpOnly cookies.
Android devices is running on API 28.
- Implement webview
- Get cookies
useEffect(() =>< let getCookies = () =>CookieManager.getAll(useWebKit).then((cookies) =>< console.log('CookieManager.get =>‘, cookies); >); if (Platform.OS === ‘android’) < getCookies = () =>CookieManager.get(‘https://linkedin.com’).then((cookies) =>< console.log('CookieManager.get =>‘, cookies); >); > getCookies(); >, []);
The text was updated successfully, but these errors were encountered:
marf commented Oct 27, 2020 •
Hello @cody0203 , have you found a solution?
geroale commented Oct 27, 2020
Same issue here
cody0203 commented Oct 29, 2020
Nah, still stuck in there
roeycohen commented Nov 2, 2020
Hi @cody0203,
I’m experiencing a problem where CookieManager.get(‘https://linkedin.com’) get all cookies but all are with httpOnly=false (even though some of them are differently true).
Is that the same for you?
cody0203 commented Nov 3, 2020
@roeycohen yes. It get only httpOnly=false on android devices.
roeycohen commented Nov 3, 2020 •
Hi @cody0203,
10x for answering!
Do you know if it means that you can’t set httpOnly cookie as well?
Update: setting httpOnly seems to work (at least for android N and above)
cody0203 commented Nov 3, 2020
Hi @cody0203,
10x for answering!
Do you know if it means that you can’t set httpOnly cookie as well?
Update: setting httpOnly seems to work (at least for android N and above)
Oh i only need to get it.
hengkx commented Nov 10, 2020
ios need get httponly cookie
cody0203 commented Nov 11, 2020
@hengkx Ios still can get httpOnly cookie, try to use CookieManager.getAll(true).then(. ) .
hengkx commented Nov 11, 2020
@hengkx Ios still can get httpOnly cookie, try to use CookieManager.getAll(true).then(. ) .
Thanks. The simulator can get. the real machine can’t get cookies.
cody0203 commented Nov 11, 2020
Thanks. The simulator can get. the real machine can’t get cookies.
Two months ago when i still development my old app, i remember i still can get it in real device. But for now, i can’t confirm that, sorry.
marf commented Nov 11, 2020 •
Hello, we can confirm that with CookieManager.getAll(true).then(. ) we can get all cookies in iOS, the problem is that there is no such function in Android we are not able to the all the cookies (even the httpOnly ones) on Android devices. Hope there is a solution for that which can make Android & iOS behave the same.
cody0203 commented Nov 11, 2020 •
@marf I think this issue become from Android native code, in class CookieManager , not from this library.
marf commented Nov 11, 2020
@marf I think this issue become from Android native code, in class CookieManager , not from this library.
@cody0203 do you think that in android there is no library which allows this or simply we have to fork CookieManager to allow this kind of behavior the same as in iOS?
cody0203 commented Nov 11, 2020
@marf I think this issue become from Android native code, in class CookieManager , not from this library.
@cody0203 do you think that in android there is no library which allows this or simply we have to fork CookieManager to allow this kind of behavior the same as in iOS?
I don’t know if any android’s library can do it but i have tried to re config CookieManager in android code and nothing happen.
In android official docs doesn’t mention about this feature too.
Sry for my bad English, wish you can understand.
marf commented Nov 11, 2020
@marf I think this issue become from Android native code, in class CookieManager , not from this library.
@cody0203 do you think that in android there is no library which allows this or simply we have to fork CookieManager to allow this kind of behavior the same as in iOS?
I don’t know if any android’s library can do it but I have tried to re config CookieManager in android code and nothing happens.
In android official docs don’t mention this feature too.
Sry for my bad English, wish you can understand.
I am not an English native speaker too 🙂
The only thing I have found is this answer from StackOverflow:
It suggests using reflection, but it is quite old and a comment said that it does not work, so I am not sure if this may be a solution.
cody0203 commented Nov 11, 2020 •
@marf I think this issue become from Android native code, in class CookieManager , not from this library.
@cody0203 do you think that in android there is no library which allows this or simply we have to fork CookieManager to allow this kind of behavior the same as in iOS?
I don’t know if any android’s library can do it but I have tried to re config CookieManager in android code and nothing happens.
In android official docs don’t mention this feature too.
Sry for my bad English, wish you can understand.
I am not an English native speaker too 🙂
The only thing I have found is this answer from StackOverflow:
It suggests using reflection, but it is quite old and a comment said that it does not work, so I am not sure if this may be a solution.
I tried and it does not work 🙂
rizkiandrianto commented Jan 17, 2021
@marf I think this issue become from Android native code, in class CookieManager , not from this library.
@cody0203 do you think that in android there is no library which allows this or simply we have to fork CookieManager to allow this kind of behavior the same as in iOS?
I don’t know if any android’s library can do it but I have tried to re config CookieManager in android code and nothing happens.
In android official docs don’t mention this feature too.
Sry for my bad English, wish you can understand.
I am not an English native speaker too 🙂
The only thing I have found is this answer from StackOverflow:
Get HttpOnly Cookies Android
It suggests using reflection, but it is quite old and a comment said that it does not work, so I am not sure if this may be a solution.
I tried and it does not work 🙂
Maybe only works for old android version?
cody0203 commented Jan 18, 2021
@marf I think this issue become from Android native code, in class CookieManager , not from this library.
@cody0203 do you think that in android there is no library which allows this or simply we have to fork CookieManager to allow this kind of behavior the same as in iOS?
I don’t know if any android’s library can do it but I have tried to re config CookieManager in android code and nothing happens.
In android official docs don’t mention this feature too.
Sry for my bad English, wish you can understand.
I am not an English native speaker too 🙂
The only thing I have found is this answer from StackOverflow:
Get HttpOnly Cookies Android
It suggests using reflection, but it is quite old and a comment said that it does not work, so I am not sure if this may be a solution.
I tried and it does not work 🙂
Maybe only works for old android version?
Источник
Проблема с файлами cookie в Android WebView
У меня есть сервер, который отправляет моему приложению Android файл cookie сеанса, который будет использоваться для аутентифицированной связи. Я пытаюсь загрузить WebView с URL-адресом, указывающим на тот же сервер, и пытаюсь передать файл cookie сеанса для аутентификации. Я замечаю, что он работает с перебоями, но не знаю почему. Я использую один и тот же файл cookie сеанса для выполнения других вызовов на моем сервере, и они никогда не завершают проверку подлинности. Я наблюдаю эту проблему только при попытке загрузить URL-адрес в WebView, и это происходит не каждый раз. Очень неприятно.
Ниже приведен код, который я использую для этого. Любая помощь будет оценена.
Спасибо, justingrammens ! Это сработало для меня, мне удалось поделиться файлом cookie в моих запросах DefaultHttpClient и активности WebView:
Спасибо Android за испорченное воскресенье. . . Вот что исправило мои приложения (после того, как вы запустите свой веб-просмотр)
Я должен сказать, что приведенные выше ответы, вероятно, сработают, но в моей ситуации, когда Android перешел на версию 5 +, мои приложения javascript для android webview умерли.
Решение: Webview CookieSyncManager
решение — дать Android достаточно времени для обработки файлов cookie. Вы можете найти дополнительную информацию здесь: http://code.walletapp.net/post/46414301269/passing-cookie-to-webview
Я бы сохранил этот файл cookie сеанса в качестве предпочтения и принудительно повторно заселил им диспетчер файлов cookie. Похоже, что cookie сеанса не переживает перезапуск активности
Я потратил большую половину из трех часов, работая над очень похожей проблемой. В моем случае у меня было несколько вызовов, которые я сделал веб-сервису, используя DefaulHttpClient а затем я хотел установить сеанс и все другие соответствующие файлы cookie в моем WebView .
Я не знаю, решит ли это вашу проблему, поскольку я не знаю, что getCookie() делает ваш метод, но в моем случае мне действительно пришлось позвонить.
Сначала удалите файл cookie сеанса, а затем снова добавьте его. Я обнаружил, что когда я пытался установить JSESSIONID файл cookie, не удаляя его предварительно, значение, которое я хотел установить, не сохранялось. Не уверен, что это поможет вам в конкретной проблеме, но подумал, что поделюсь тем, что нашел.
После некоторого времени исследований я собрал несколько фрагментов, которые помогли мне прийти к этому решению. После того, как CookieSyncManager устарел, это может быть лучшим способом установить конкретный файл cookie для веб-просмотра в Kotlin в настоящее время, вам больше ничего не понадобится.
У меня здесь другой подход, чем у других людей, и это подход, который гарантированно работает без использования CookieSyncManager (где вы находитесь во власти семантики типа «Обратите внимание, что даже sync () происходит асинхронно»).
По сути, мы переходим к правильному домену, а затем выполняем javascript из контекста страницы, чтобы установить файлы cookie для этого домена (так же, как и сама страница). У этого метода есть два недостатка: это может привести к дополнительному времени прохождения туда и обратно из-за дополнительного HTTP-запроса, который вы должны сделать; и если на вашем сайте нет эквивалента пустой страницы, он может высветить любой URL-адрес, который вы загружаете первым, прежде чем перенаправить вас в нужное место.
Если вы доверяете домену, из которого находятся файлы cookie, вы можете обойтись без apache commons, но вы должны понимать, что это может представлять риск XSS, если вы не будете осторожны.
Это рабочий фрагмент кода.
Здесь httpclient — это объект DefaultHttpClient, который вы использовали в запросе HttpGet / HttpPost. Также нужно убедиться, что имя и значение файла cookie должны быть указаны
setCookie установит cookie для данного URL.
Я волшебным образом решил все свои проблемы с файлами cookie с помощью этой строки в onCreate:
изменить: сегодня он перестал работать. 🙁 какая хрень, android.
С этим тоже столкнулся. Вот что я сделал.
В моем LoginActivity внутри моей AsyncTask у меня есть следующее:
// ГДЕ CookieStoreHelper.sessionCookie — это еще один класс, содержащий переменную sessionCookie, определенную как List cookies; и cookieStore определяют как BasicCookieStore cookieStore;
Затем на моем фрагменте, где находится мой WebView, у меня есть следующее:
внутри моего метода или непосредственно перед тем, как вы установите WebViewClient ()
Совет: установите firebug в firefox или используйте консоль разработчика в Chrome и сначала протестируйте свою веб-страницу, запишите файл cookie и проверьте домен, чтобы вы могли его где-нибудь сохранить, и убедитесь, что вы правильно устанавливаете правильный домен.
Источник
Как загрузить страницу в WebView с куками?
Есть ссылка на определенную страницу (https://. ), которую надо отобразить в WebView. Сайт с авторизацией, авторизационные куки есть (их отдает веб сервис). Но вместо загрузки нужной страницы постоянно получаю отлуп на страницу ввода логина.
Пробовал по всякому, ничего не помогло.
где cookies — авторизационные куки.
На счет второго варианта иллюзий не питал, в документации ясно сказано: Note that if this map contains any of the headers that are set by default by this WebView, such as those controlling caching, accept types or the User-Agent, their values may be overriden by this WebView’s defaults.
Может кто-то из знающих подскажет, в чем проблема или же подскажет, как правильно реализовать загрузку страницы с авторизационными куками?
- Вопрос задан более трёх лет назад
- 6821 просмотр
Проблема решается перекрытием в WebViewClient метода shouldInterceptRequest(). WebView подставляет куки не во все запросы (в частности при обращении к ресурсам типа картинок, js, css, . не подставляет), из-за чего имеем описанную выше проблему.
У конструктора WebResourceResponse первые два параметра mimeType и encoding, которые мы можем получить из заголовка response. Но в моем случае, чёрт знает по какой причине, если передавать их в конструктор — получаю 400 Bad Request.
Может не совсем в тему. Бадался с cookie в своем приложении, использовал Retrofit 2 и OkHttp3 (сервер тоже свой — nginx), сколько ни пробовал примеров с getDefaultSharedPreferences() не получалось сохранить ничего кроме PHPSESSID. Решил вручную записывать через SharedPreferences editor.putString(name, value ); научился сохранять и посылать cookie, но сервер не всегда адекватно на них реагировал: заметил, что если PHPSESSID стоит в конце списка посылаемых cookie, то все нормально, иначе сервер высылает код новой сессии. Когда сложил все cookie в одну строку все заработало.
public class AddCookiesInterceptor implements Interceptor <
public static final String PREF_COOKIES = «PREF_COOKIES»;
// We’re storing our stuff in a database made just for cookies called PREF_COOKIES.
// I reccomend you do this, and don’t change this default value.
private Context context;
public AddCookiesInterceptor(Context context) <
this.context = context;
>
@Override
public Response intercept(Interceptor.Chain chain) throws IOException <
Request.Builder builder = chain.request().newBuilder();
Log.i(«MyCookie»,»————————————«);
G_.cookie = PrefStorage.getAllProperty();
String val=»»;
for(Map.Entryentry : G_.cookie.entrySet()) <
val += (String)entry.getValue()+»; «;
>
builder.addHeader(«Cookie», val);
Log.i(«MyCookie»,val);
Log.i(«MyCookie»,»————————————«);
public class ReceivedCookiesInterceptor implements Interceptor <
private Context context;
public ReceivedCookiesInterceptor(Context context) <
this.context = context;
> // AddCookiesInterceptor()
@Override
public Response intercept(Chain chain) throws IOException <
Response originalResponse = chain.proceed(chain.request());
if (!originalResponse.headers(«Set-Cookie»).isEmpty()) <
String tmp;
for(String header : originalResponse.headers(«Set-Cookie»)) <
tmp = header.split(«=»)[0];
PrefStorage.addProperty(tmp, header);
>
>
public class PrefStorage < // обязательно инициализировать
public static final String STORAGE_NAME = «StorageName»;
private static SharedPreferences settings = null;
private static SharedPreferences.Editor editor = null;
private static Context context = null;
public static void init( Context cntxt ) <
context = cntxt;
>
Источник