java - 以编程方式从 WebView 登录

标签 java android apache

在我的 Android 应用程序中,我使用 WebView 访问服务器提供的一些网络 map 数据。服务器需要一些基于 HTTP 表单的身份验证以允许访问这些数据。由于该网站没有移动版本,显示登录页面(或任何其他页面)看起来很糟糕。不幸的是,我无法访问该站点,因此我想到了以下方法:

  • 使用 native 用户界面收集用户名和密码
  • 认为一个 Http post 将这些信息发送到服务器
  • 收到响应后获取服务器发送的cookie
  • 将 cookie 设置为 WebView
  • 尝试最终访问所需的数据

现在我只是想通过登录阶段。

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

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

一个。认证部分

 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.设置 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");

     }

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

最佳答案

1) 先尝试发起HttpGet请求,获取cookies,然后进行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();

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

关于java - 以编程方式从 WebView 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5898154/

相关文章:

Android BroadcastReceiver 设置闹钟

php - PHP脚本不断“重启”以创建自身的新实例

php - 使用 URL 参数和 XSendFile 在浏览器中缓存图像

php - 除了证书,我还需要什么 SSL?

java - 是否可以在不需要互联网的情况下使用 Spring Java 项目?

java - 使用数组来决定谁是活跃玩家(回合制猜谜游戏)

java - 为什么我的 XML 解析器不打开连接?

android - 如何在 android 中单击 TextView 超链接打开 Google 页面?

Java:ConcurrentModificationException,3个线程,不同的列表,相同的对象

android - 如何在AlertDialog android中获取RadioGroup的选定索引