Android:使用Http客户端和Webview自动登录(wordpress站点)



这是我第一次制作Android应用程序,可能是我第五次接触Java,所以请耐心等待。我的目标是制作一个移动应用程序,让用户登录wordpres(我们学校使用的一个网站,所以他们不是管理员,只是有效用户),除其他外,但登录时我遇到了障碍。

此外,在整个过程中,我借用了我发现的以前SO问题的代码,如果我能再次找到它们,我将链接到整个过程中。

问题:我的方法(感谢谷歌和这个网站上的许多帖子)包括使用HttpClient发出http Post请求并登录网站,然后我的目标是将cookie转移到Webview,这样我的用户就不必手动登录了。

全局vars:myWebView和httpClient

出于测试目的,我在操作系统主线程异常/错误上覆盖了网络

我的大部分代码都来自这里:(在android 4.4+中httpClient和webView之间的共享会话)

与上述相关的一些代码:

AppSettings类(来自SO帖子)操作cookie

public class AppSettings extends Application
{
  private static final DefaultHttpClient client = createClient();
  @Override
  public void onCreate()
  {
  }
  public static DefaultHttpClient getClient()
  {
    return client;
  }
  private static DefaultHttpClient createClient()
  {
    BasicHttpParams params = new BasicHttpParams();
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    DefaultHttpClient httpclient = new DefaultHttpClient(cm, params);
    httpclient.getCookieStore().getCookies();
    return httpclient;
  }
}

现在,在使用WebView的文件中,我放了这个,它应该完成大部分cookie操作

        myWebView.setWebViewClient(new WebViewClient()
                             {
                                 @Override
                                 public void onPageStarted(WebView view, String url, Bitmap favicon)
                                 {
                                     super.onPageStarted(view, url, null);
                                     Log.w(null, "onPage Started url is" + url);

                                     Cookie sessionInfo;
                                     List<Cookie> cookies = httpClient.getCookieStore().getCookies();
                                     if (!cookies.isEmpty())
                                     {
                                         CookieSyncManager.createInstance(DisplayMessageActivity.this);
                                         CookieManager cookieManager = CookieManager.getInstance();
                                         for (Cookie cookie : cookies)
                                         {
                                             sessionInfo = cookie;
                                             String cookieString = sessionInfo.getName() + "=" + sessionInfo.getValue()
                                                     + "; domain=" + sessionInfo.getDomain();
                                             Log.w(null, "cookie string is " + cookieString);
                                             cookieManager.setCookie("http://www.corpsofcadets.net", cookieString);
                                             CookieSyncManager.getInstance().sync();
                                             Log.w(null, "cookie loop " + cookie.getName());
                                         }
                                     }
                                     else
                                     {
                                         Log.w(null, "no cookies");
                                     }
                                 }
                             });

这是我发布数据的地方。作为一个简短的说明,这似乎是有效的,或者至少有所改进,因为在我手动设置标题之前,wordpress发回了一个HTTP406错误。现在responseBody看起来相当于登录页面的HTML(http://pastebin.com/smLJrziz),但我也看到我被分配了wordpress"test_cookie",所以一定有什么事情发生了,对吧?!

    public void postData() throws IOException, ClientProtocolException {
    httpClient = AppSettings.getClient();
    HttpPost request = new HttpPost("http://corpsofcadets.net/wp-login.php");
    request.setHeader("Accept", "*/*");
    request.setHeader("Content-Type", "application/x-www-form-urlencoded");
    request.setHeader("User-Agent", "Mozilla/5.0");
    request.setHeader("Accept-Encoding", "gzip/deflate");
    List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair("user_login", "obscured"));
    postParameters.add(new BasicNameValuePair("user_pass", "obscured"));

    try {
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters);
        request.setEntity(entity);
        HttpResponse response= httpClient.execute(request);
        if (response != null)
        {
            String responseBody = EntityUtils.toString(response.getEntity());
            Log.w(null, "responseBody " + responseBody);
        }
        else
        {
            Log.w(null, "FAIL");
        }
    } catch (Exception e)
    {
        Log.w(null, "Error sending data");
        e.printStackTrace();
    }

这可能被认为是一个意见问题,因此偏离了主题,但我刚刚偶然发现了这个SO问题(将Cookie从HttpURLConnection(java.net.CookieManager)传递到WebView(android.webkit.CookieManager)),这与HttpURLConnection结合起来会是一个更简单的解决方案吗?最后,我可以以任何方式使用XML-RPC吗?

感谢百万

不起作用的方法:Webview.loadData,Webview.posturl,用Webview.load url用javascript提交表单,这个当前设置和类似的迭代

希望这能帮助到别人,我找到了一个很好的、简单的解决方案。

尽管我曾经尝试过并质疑javascript路由,但我还是尝试了一下,它运行得很好。

我所做的不同之处在于,覆盖onPageLoaded函数,就像我在上面学到的那样,失败的方式是^,并在其中使用javascript。我还有一个静态变量(loadCount,我相信),可以确保它每个实例只登录一次,这样就不会拖低页面加载时间。

我相信,我以前遇到过它的问题,因为它没有等待页面加载,javascript正在搜索尚未加载的元素(也许?)。

这是工作代码:

    myWebView.setWebViewClient(new WebViewClient() {
                               public void onPageFinished(WebView view, String url) {
                                   loadCount = 0;
                                   if (loadCount == 0) {
                                           myWebView.loadUrl(
                                                   "javascript:document.getElementById('user_login').value = '" + prfs.getString("Username", "Incorrect credentials") + "';" +
                                                   "javascript:document.getElementById('user_pass').value = '" + prfs.getString("Password", "Incorrect credentials") + "';" +
                                                   "javascript:document.getElementById('wp-submit').click();"
                                           );
                                           loadCount++;
                                       } else if (loadCount == 1) {
                                           myWebView.loadUrl(url);
                                       }
                                   }
                               });

最新更新