以编程方式从WebView登录

ste*_*eve 8 java apache android

在我的Android应用程序中,我使用Web视图访问服务器提供的一些Web映射数据.服务器需要一些基于HTTP表单的身份验证才能访问这些数据.由于该网站没有移动版本,显示登录页面(或任何其他页面)看起来非常糟糕.不幸的是,该网站几乎无法触及,所以我想到了以下方法:

  • 使用本机用户界面来收集用户名和密码
  • 认为Http帖子将这些信息发送到服务器
  • 收到响应后,获取服务器发送的cookie
  • 将cookie设置为Web视图
  • 尝试最终访问所需的数据

现在我只想尝试通过登录阶段.

这是一个可行的解决方案,还是完全错误的,我应该尝试别的吗?

为了完整起见,我发布以下代码

A.认证部分

 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;

    }
Run Code Online (Sandbox Code Playgroud)

B.设置cookie并加载所需的页面

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

     }
Run Code Online (Sandbox Code Playgroud)

加载该页面的结果是显示login_page表单

sai*_*kek 1

1)首先尝试发出HttpGet请求,获取cookie,然后执行HttpPost。我认为这样你不应该手动添加cookie。使用一个 HttpClient 来执行此操作。

2)代替

           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();
Run Code Online (Sandbox Code Playgroud)

使用 EntityUtils.toString(response.getEntity())。