Programmatically logging in from WebView

Programmatically logging in from WebView

In my Android application I'm using a web view to access some web mapping data provided by a server. The server requires some HTTP form based authentication to allow access to those data. Due to the fact that the site doesn't have a mobile version, displaying the login page (or any other pages) looks pretty bad . Unfortunately the site is hardly into my reach so I've thought of the following approach:

In my Android application I'm using a web view to access some web mapping data provided by a server. The server requires some HTTP form based authentication to allow access to those data. Due to the fact that the site doesn't have a mobile version, displaying the login page (or any other pages) looks pretty bad . Unfortunately the site is hardly into my reach so I've thought of the following approach:

  • use a native user interface to collect the username and password
  • thought a Http post send those information to the server
  • after the response is received get the cookies the server is sending
  • set the cookies to the the web view
  • try to finally access the desired data

For now I'm just trying to pass the login phase.

Is this a viable solution , or is just plain wrong and I should try something else ?

For completeness I post the code below

A. The authentication part

private String authenticate()  throws Exception
    {
        // Create a new HttpClient and Post Header
           HttpClient httpclient = new DefaultHttpClient();
           HttpPost httppost = new HttpPost("http://mySite/login_form");

       HttpResponse response = null;
       BufferedReader in = null;
       String resultContent = null;

       try
       {
           // Add data
           List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
           nameValuePairs.add(new BasicNameValuePair("came_from", ""));
           nameValuePairs.add(new BasicNameValuePair("form.submitted", "1"));
           nameValuePairs.add(new BasicNameValuePair("js_enabled", "0"));
           nameValuePairs.add(new BasicNameValuePair("cookies_enabled", ""));
           nameValuePairs.add(new BasicNameValuePair("login_name", ""));
           nameValuePairs.add(new BasicNameValuePair("pwd_empty", "0"));
           nameValuePairs.add(new BasicNameValuePair("name", "username"));
           nameValuePairs.add(new BasicNameValuePair("password", "password"));

           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Create a local instance of cookie store
            CookieStore cookieStore = new BasicCookieStore();
            // Create local HTTP context
            HttpContext localContext = new BasicHttpContext();
            // Bind custom cookie store to the local context
            localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
           // Execute HTTP Post Request
           response = httpclient.execute(httppost,localContext);

           in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
           StringBuffer sb = new StringBuffer("");
           String line = "";
           String NL = System.getProperty("line.separator");
           while ((line = in.readLine()) != null)
           {
             sb.append(line + NL);
           }
           in.close();
           resultContent = sb.toString();
           Log.i("mytag","result :"+resultContent);

           cookies = new java.util.ArrayList();
           cookies = cookieStore.getCookies();

       }
       catch (ClientProtocolException e)
       {
           Log.i("mytag","Client protocol exception");
       }
       catch (IOException e)
       {
           Log.i("mytag","IOException");
       }
       catch(Exception e)
       {
           Log.i("mytag","Exception");
           Log.i("mytag",e.toString());
       }


    return resultContent;

}

B. Setting the cookies and loading the desired page

private void init()
{
            CookieSyncManager.createInstance(this);
            CookieManager cookieMan= CookieManager.getInstance();
            cookieMan.setAcceptCookie(true);
            cookies = StartupActivity.listAfter;

        if(cookies != null)
        {
            for (int i = 0; i<cookies.size(); i++)
            {
                Cookie cookie = cookies.get(i);
                cookieMan.setCookie("cookie.getDomain()",cookie.getValue());
            }
        }
        CookieSyncManager.getInstance().sync();

        webView = (WebView)findViewById(R.id.web_view);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.setWebViewClient(new HelloWebViewClient());

}

 protected void onResume()
 {
        super.onResume();    

        // test if the we logged in
        webView.loadUrl("mySite/myDesiredFeature");

 }

The results of loading that page is that the login_page form is displayed

android java

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Top Android Projects with Source Code

Android projects with source code - Work on real-time android projects. We’ll start project ideas from beginners level and later move to advance projects.

Building Dark Mode Theme in Android

Hello World, today we are going to see how we can implement a dark theme or night mode in our android application. This tutorial is going to be very simple and easy to understand. The dark theme is attractive to users and it is comfortable for low light conditions.

Top 130 Android Interview Questions - Crack Technical Interview Now!

Top Android Interview Questions & Answers from Beginner to Advanced level. Get ready to crack your next android interview with these android interview questions

Android Menu - Steps to implement Menu in Android - DataFlair

Implement Android Menu in your application - Provide functionality to your application and make it user friendly. Also, Learn its types and implementation.

Android Hello World Program - Create Your First App in Android Studio

Learn how to start android development in android studio. This is a very simple android project & doesn't need to do much coding