Как установить 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 работает. Надеюсь, это поможет кому-то другому
Источник
Как сохранить файл cookie в Android webview навсегда?
С моим кодом ниже, я смог сохранить файл cookie, но как только я закрываю приложение, файл cookie исчезает.
Как это вызвано и как я могу решить это?
3 ответов
вы должны сказать CookieSyncManager для синхронизации после загрузки страницы в вопрос. В вашем примере кода onCreate метод выполняется полностью перед WebView пытается загрузить страницу, поэтому процесс синхронизации (который происходит асинхронно), вероятно, завершится до загрузки страницы.
вместо этого скажите CookieSyncManager синхронизировать onPageFinished в WebViewClient. Это даст тебе то, что ты хочешь.
В Документация CookieSyncManager хорошо читать, как это сделать правильно.
вот как вы можете настроить реализацию WebViewClient, чтобы сделать это за вас:
вам не нужно будет говорить CookieSyncManager синхронизировать в другом месте с этим на месте. Я не проверял это, так что дайте мне знать, если это работает.
.sync () должен принудительно синхронизировать imediate и должен вызываться после загрузки страницы ,потому что он синхронизирует ОЗУ с кэшем , поэтому cookie должен быть в ОЗУ перед вызовом .
система автоматически синхронизирует его каждые 5 минут, если вы используете эту схему
Я думаю, что вы не ждали 5 минут, поэтому сохраните файл cookie.
для тех, кто сталкивается с проблемами с CookieManager класс, чтобы cookie сохранялся даже после закрытия приложения, они должны попробовать flush() функции CookieManager .
обратите внимание, что я не пробовал это, поэтому, если это работает, пожалуйста, дайте мне знать тоже.
согласно документации android
гарантирует, что все файлы cookie, доступные в настоящее время через API getCookie, записываются в persistent место хранения. Этот вызов будет блокировать вызывающего абонента, пока это не будет сделано и может выполнять ввод-вывод
и в CookieSyncManager documnentation написано, что:
этот класс устарел на уровне API 21. Теперь WebView автоматически синхронизирует файлы cookie по мере необходимости. Вам больше не нужно создавать или использовать CookieSyncManager. Чтобы вручную принудительно синхронизировать, вы можете использовать метод CookieManager flush (), который является синхронной заменой sync(). CookieSyncManger ссылка
Источник
Как очистить cookie в webview
WebView сохранить cookie
Здравствуйте. Нужно реализовать OAuth 2.0 для вк. В принципе разобрался, токен из адреса выдрал, но.
Достаточно БЫСТРАЯ загрузка cookie для WebView
Всем добрый день, в моём приложение сделал мини-браузер. Но осталось реализовать сохранение и.
Почему Cookie в куки заносится значение, а в другом файле Cookie пуста?
Здравствуйте подскажите что я не так делаю все вроде по примерам да ошибок как токавых нет.. но не.
Решение
Проблемы с передачей Cookie (очистка Cookie)
Всем привет! Кто нибудь пытался реализовать обмен с сайтом с авторизацией и сохранением Cookie.
Как парсить WebView?
webView.loadUrl(«file:///android_asset/test/index.html»);ну вот так я его инициализирую, там.
Django csrf cookie —нужно определить в чем ошибка CSRF cookie not set
НУжна помощь в определений ошибки как исправить в папке Templates находится файл index.py.
Как подключить WebView в приложение?
Прочитал инструкцию на официальном сайте: http://developer.android.com/guide/webapps/webview.html.
Как вывести содержимое WebView в qml?
Собственно в заголовке весь вопрос. Есть WebView, в нем загружен сайт, нужно получить html-текст.
Источник
Как загрузить страницу в 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.
Может кто-то из знающих подскажет, в чем проблема или же подскажет, как правильно реализовать загрузку страницы с авторизационными куками?
- Вопрос задан более трёх лет назад
- 6824 просмотра
Проблема решается перекрытием в 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;
>
Источник
Android cookies from webview
Asked by:
Question
I received a request this morning to share how I set cookies in a webview so here it is, hope it’s helpful. It’s worked for me so far but feel free to comment on it if it can be improved. First, you have to create a custom render for your webview in iOS and Android, there are many examples of how to do that so I won’t go into that here.
In my shared code I have a UserInfo object that contains a CookieContainer:
In my (native) login page I have an event called OnLoginClickAsync which validates the login information. I create a HTTPClientHandler:
Then save the resulting CookieContainer if the validation is successful:
On the Android side in the OnElementChanged event for my web view renderer I use:
On the iOS side in the OnElementChanged event for my web view renderer I use:
Also, if you want to use the cookie container in a straight call — not in a webview — just set it in the handler:
All replies
Very helpful; thank you!
Many thanks indeed! :smiley:
@ChristineBlanda (or someone else who got this working) If not too much asking, can you post a complete solution (a zip file, or github, as convienient for you) with this example, with the complete iOS and Android code? Would be much appreciated. Thank you
I figured it out.
in my case I also had a CustomWebView, and was using a CustomWebVierRenderer.
Just like in this post: http://forums.xamarin.com/discussion/comment/109137/#Comment_109137 Instead of TransparentWebViewRenderer in my case: CustomWebVierRenderer. Else exactly the same.
For Android I had it working, my problem was with iOS. I created this method:
protected override void OnElementChanged(ElementChangedEventArgs e)
SetSessionCookies method = the iOS code provided in this post (// Set cookies here)
Really appreciate your help with this! Small change to your android renderer, since RemoveAllCookie() is deprecated now, would be to use RemoveAllCookies() and then pass in either null or pass in an actual callback to find out when and if any cookies were deleted and do any other actions needed. See the Android documentation below for more details:
I just noticed that for some reason in my post above «this post» didn’t link the post, so here it is:
@ChristineBlanda Thanks again for the code above. It seems to be working great but I wanted to know how you are actually assigning your collection of cookies to be used in the WebView on both platforms?
@hvaughan I am grabbing and passing back cookies that are passed in on a previous web call (when the user is authenticated)
Very helpful, but a couple of comments. First, NSHttpCookie(netCookie) does not seem to copy the Expiry so using the constructor like that didn’t work for me for cookies that should persist between sessions. Secondly, this code doesn’t necessarily need to live in a WebView renderer. In my case, I get the cookies from a REST call, and then want to use them in a WebView; in that case no customization of WebView is needed at all (on iOS, I add cookies to NSHttpCookieStorage.SharedStorage before the WebView is created).
@PaoloBrocco ciao paolo sei per caso italiano? ho qualche problema con questo topic, potresti darmi qualche dritta per favore?
@DanielL hi Daniel, i’ve tried the cookieWebView, but i got 2 issue, when i try to add a cookie to the Cookies collection it crashes because it says the object is null. The second issue is that i can’t intercept the navigating item. can you help me please?
@andreacurti — I did a blog post on something similar with accessing cookies from a PCL, at
it’s pretty basic (I needed it for the bare minimum) but may also help point you in the right direction. All it does is inject the platform-specific cookie manager so you can do stuff with it. If you need to add functionality, just add your new method name to the interface, and implement it in your platform code. Then you can call that method from your shared code.
Below is my complete implementation of a custom WebView that accepts Cookie. I needed the authentication cookies I get from authenticating my app using HttpClient. The solution is based from ChristineBlanda’s 🙂
First, I created a CookieWebView class to be able to set and share the cookie between platforms.
And then my implementation for my IOS renderer is show below. By the way, if you are planning to use ViewRenderer instead of WebViewRenderer as you need to use WKWebView instead of UIWebView. Take note that there is a problem accessing cookies in NSHttpCookieStorage.SharedStorage. Please refer to stackoverflow.com/questions/24464397/how-can-i-retrieve-a-file-using-wkwebview/24982211#24982211
Below is my implementation for Android Renderer:
To use this in your Page:
In the code behind of my page, I set the cookies needed from my Login Page:
I set the CookieJar values during the Login Method in my Helper Class:
I hope this helps you 🙂
@kishang what about UWP .
@RefkaBenmahmoud Take a look at this https://xamarinhelp.com/cookie-sharing-webview-http-client/
Thank you @ChristineBlanda and @kishang!
@MarlonRibeiro why using webview, this will lose the native approach of xamarin, to web approach !
@ChristineBlanda can you please explain to me why you used webview? is it possible without webview please take a look at this : https://forums.xamarin.com/discussion/94221/cant-access-to-the-cookies#latest
@RefkaBenmahmoud I don’t think I understand your question .. I am using a webview to display content that is only available as web page.
@RefkaBenmahmoud Hi, I’m going to use webview to get authorization of Amazon login to my app to sync with Amazon Echo. It would be great if Xamarin provided binded nuget for LoginWithAmazon SDK but they don’t. So I decided to use webview instead bind Native library myself.
And Thanks for your sharing. It will be much helpful! @ChristineBlanda
@kishang your iOS version worked fine for me, Android one caused problems(cookies weren’t always added, or were added «too late»). I solved it by doing everything in OnElementChanged instead of OnPageStarted.
Has anyone had any success getting this implementation to work with XLabs HybridWebView? The HybridWebViewRenderer for Xlabs doesn’t seem to have an OnElementChanged.
@ChristineBlanda and @kishang — thank you both for providing an excellent tutorial and example of setting Cookies in a WebView. I wanted to ask about a variation. In my application, first a web page call using an httpclient is made and I get back an expected response that includes a session cookie. Then, I want to use a webview to display a webpage that includes ajax calls made in javascript that are used in setting up that page. I need to pass along that session cookie and have them used in the ajax calls for authentication/security.
I’ve set up a modified webView based the example code you both provided. I can see that the initial http request made of the second webpage includes the cookie (I have access to the web server). However, as that page is being brought in and javascript is executed, the first ajax call made from that webpage does not include the cookie. In searching online and in trying experiments, I’ve added in most of the overrides available for a WebViewClient but I’ve not been able to find a way to intercept the ajax calls on the webpage in order to set the session cookie. It would be great if the «ShouldInterceptRequest» override method would work, but the ajax calls made from javascript on the webpage don’t seem to trigger this. I think it must only work for links clicked on by the user. Any guidance on how to proceed? I can’t imagine that this is an unusual use case, but so far haven’t been able to cobble together a solution despite doing lots of searching online.
@»SteveHenry.5430″ I have not experienced that issue. I use javascript and ajax quite a bit in my pages, and have not had any authentication issues. Are you experiencing this on a particular platform?
Источник