Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • 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

like image 855
steve Avatar asked May 05 '11 13:05

steve


1 Answers

1) Try first to make HttpGet request, to get cookies, then perform HttpPost. I think this way you should not add cookies manually. Use one HttpClient to do this.

2) Instead of

           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();

use EntityUtils.toString(response.getEntity()).

like image 134
saikek Avatar answered Oct 17 '22 13:10

saikek