Android webview set cookie

I’m getting a HttpResponse from a server when checking if a username or password is correct. When I load the url in a webview I want the webView to have the cookie (the answer I get with postData() stored in the webView . I want the webView to pickup the cookie and load the url with that cookie stored in the webview.

I’m getting the response through.

And I loadUrl with:

I guess I’m not really managing a cookie and I have no idea how to do so. Any suggestions or solutions?

5 Answers 5

It’s quite simple really.

where cookieString is formatted the same as a more traditional Set-Cookie HTTP header, and baseUrl is the site the cookie should belong to.

Couple of comments which I found out from my experience and gave me headaches:

  1. http and https urls are different. Setting a cookie for http://www.example.com is different than setting a cookie for https://www.example.com
  2. A slash in the end of the url can also make a difference. In my case https://www.example.com/ works but https://www.example.com does not work.
  3. CookieManager.getInstance().setCookie is performing an asynchronous operation. So, if you load a url right away after you set it, it is not guaranteed that the cookies will have already been written. To prevent unexpected and unstable behaviours, use the CookieManager#setCookie(String url, String value, ValueCallback callback) (link) and start loading the url after the callback will be called.

I hope my two cents save some time from some people so you won’t have to face the same problems like I did.

Источник

WebView and Cookies on Android

I have an application on appspot that works fine through regular browser, however when used through Android WebView, it cannot set and read cookies. I am not trying to get cookies «outside» this web application BTW, once the URL is visited by WebView, all processing, ids, etc. can stay there, all I need is session management inside that application. First screen also loads fine, so I know WebView + server interactivity is not broken.

I looked at WebSettings class, there was no call like setEnableCookies.

I load url like this:

5 Answers 5

If you are using Android Lollipop i.e. SDK 21, then:

won’t work. You need to use:

I ran into same issue and the above line worked as a charm.

The CookieSyncManager is used to synchronize the browser cookie store between RAM and permanent storage. To get the best performance, browser cookies are saved in RAM. A separate thread saves the cookies between, driven by a timer.

To use the CookieSyncManager , the host application has to call the following when the application starts:

Читайте также:  X plore для андроида 4pda

To set up for sync, the host application has to call

in Activity.onResume(), and call

To get instant sync instead of waiting for the timer to trigger, the host can call

The sync interval is 5 minutes, so you will want to force syncs manually anyway, for instance in onPageFinished(WebView, String). Note that even sync() happens asynchronously, so don’t do it just as your activity is shutting down.

Источник

Я хочу вызвать один конкретный 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 работает. Надеюсь, это поможет кому-то другому

Источник

Как загрузить страницу в 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.

Читайте также:  Как раздать вай фай с андроида самсунг а31

Может кто-то из знающих подскажет, в чем проблема или же подскажет, как правильно реализовать загрузку страницы с авторизационными куками?

  • Вопрос задан более трёх лет назад
  • 6820 просмотров

Проблема решается перекрытием в 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;
>

Источник

Why does Android WebView sporadically not sending my session cookie?

I have a server that sends my android app a session cookie to be used for authenticated communication. I am trying to load a WebView with a URL pointing to that same server and I’m trying to pass in the session cookie for authentication. I am observing that it works intermittently but I have no idea why. I use the same session cookie to make other calls on my server and these never fail authentication. I only observe this problem when trying to load a URL in a WebView, and it does not happen every time. Very frustrating.

Читайте также:  Weather pro для android

Below is the code that I’m using to do this. Any help will be greatly appreciated.

16 Answers 16

Thanks justingrammens! That worked for me, I managed to share the cookie within my DefaultHttpClient requests and WebView activity:

Thanks Android for ruining my Sunday . . . Heres what fixed my Apps ( after you init your webview )

I should say the above answers will probably work but in my situation the moment Android went v5+ my android webview javascript ‘apps’ died.

the solution is to give the Android enough time to proccess cookies. You can find more information here: http://code.walletapp.net/post/46414301269/passing-cookie-to-webview

I would save that session cookie as a preference and forcefully repopulate the cookie manager with it. It sounds that session cookie in not surviving Activity restart

I’ve spent the greater half of 3 hours working on a very similar issue. In my case I had a number of calls, that I made to a web service using a DefaulHttpClient and then I wanted to set the session and all other corresponding cookies in my WebView .

I don’t know if this will solve your problem, since I don’t know what your getCookie() method does, but in my case I actually had to call.

First to remove the session cookie and then re-add it. I was finding that when I tried to set the JSESSIONID cookie without first removing it, the value I wanted to set it to wasn’t being save. Not sure if this will help you particular issue, but thought I’d share what I had found.

After some time researching I’ve gathered some pieces that made me get to this solution. Once that CookieSyncManager is deprecated, this may be the best way to set a specific cookie for a webview in Kotlin nowadays, you shouldn’t need anything else.

Couple of comments (at least for APIs >= 21) which I found out from my experience and gave me headaches:

  1. http and https urls are different. Setting a cookie for http://www.example.com is different than setting a cookie for https://www.example.com
  2. A slash in the end of the url can also make a difference. In my case https://www.example.com/ works but https://www.example.com does not work.
  3. CookieManager.getInstance().setCookie is performing an asynchronous operation. So, if you load a url right away after you set it, it is not guaranteed that the cookies will have already been written. To prevent unexpected and unstable behaviours, use the CookieManager#setCookie(String url, String value, ValueCallback callback) (link) and start loading the url after the callback will be called.

I hope my two cents save some time from some people so you won’t have to face the same problems like I did.

Источник

Оцените статью