A
A
Andrey2015-07-16 19:28:08
Android
Andrey, 2015-07-16 19:28:08

How to load page in webview with cookies?

There is a link to a specific page ( https://....) that needs to be displayed in the WebView. A site with authorization, there are authorization cookies (they are given by the web service). But instead of loading the desired page, I constantly get a thump on the login page.
Tried everything, nothing helped.
Option 1:

CookieManager manager = CookieManager.getInstance();

        manager.setAcceptCookie(true);
        manager.setCookie(url, cookies);

        CookieSyncManager.getInstance().sync();
        webView.loadUrl(url);

where cookies are authorization cookies.
Option #2:
headers.put("Cookie", authCookies);

...

webView.loadUrl(url, headers);

I had no illusions about the second option, the documentation clearly states: 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.
Can someone who knows tell me what the problem is or tell me how to correctly implement the loading of the page with authorization cookies?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey, 2015-07-24
@kozinakoff

The problem is solved by overriding the shouldInterceptRequest () method in the WebViewClient. WebView does not set cookies in all requests (in particular, when accessing resources such as images, js, css, ... it does not set cookies), which is why we have the problem described above.

OkHttpClient client = new OkHttpClient();

    Request req = new Request.Builder()
                            .url(url)
                            .addHeader(HttpHeaders.USER_AGENT, Constants.USER_AGENT_VALUE)
                            .addHeader(HttpHeaders.COOKIE, cookies)
                            .build();

    Response response = client.newCall(req).execute();

    InputStream responseInputStream = response.body().byteStream();

    return new WebResourceResponse(null, null, responseInputStream);

The WebResourceResponse constructor has the first two parameters mimeType and encoding, which we can get from the response header. But in my case, the devil knows for what reason, if I pass them to the constructor, I get 400 Bad Request.

A
Alexander, 2015-07-23
@fuliozor

I am using the following code:

CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setCookie(url, "sid=" + sid);

webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);

A
antonsheva80, 2021-01-12
@antonsheva80

Maybe not quite in the subject ... I was having trouble with cookies in my application, I used Retrofit 2 and OkHttp3 (the server is also my own - nginx), no matter how I tried examples with getDefaultSharedPreferences(), I could not save anything except PHPSESSID. Decided to manually write via SharedPreferences editor.putString(name, value ); I learned how to save and send cookies, but the server did not always respond adequately to them: I noticed that if PHPSESSID is at the end of the list of cookies to be sent, then everything is fine, otherwise the server sends a new session code. When I put all the cookies in one line, everything worked.
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 recommend 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","------------------------------");
return chain.proceed(builder.build());
}
}
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);
}
}
return originalResponse;
}
}
public class PrefStorage { // be sure to initialize
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;
}
private static void init(){
settings = context.getSharedPreferences(STORAGE_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
}
public static void addProperty( String name, String value ){
if( settings == null ){
init();
}
editor.putString(name, value);
editor.commit();
}
public static String getProperty( String name ){
if( settings == null ){
init();
}
return settings.getString( name, null );
}
public static Map getAllProperty(){
if( settings == null ){
init();
}
return settings.getAll();
}
}
private NetworkService() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder client = new OkHttpClient.Builder()
.addInterceptor(new AddCookiesInterceptor(getApplicationContext()))
.addInterceptor(new ReceivedCookiesInterceptor(getApplicationContext()))
.addInterceptor(interceptor);
mRetrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client.build())
.build();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question