如何使用android webview中的代码发送POST数据

jav*_*ava 31 post android login http webview

我有一个由a组成的android应用程序,WebWiew我需要使用代码自动登录到站点.我尝试使用postUrl()它似乎工作......但只在某些网站上.

这是我正在使用的代码:

public class webviewActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WebView webview = new WebView(this);
        setContentView(webview);
        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);

        webview.setWebViewClient(new WebViewClient());

        String postData = "login_email=myEmail@gmail.com&login_password=myPassword";
        webview.postUrl("https://www.dropbox.com/login", EncodingUtils.getBytes(postData, "utf-8"));
    }
}
Run Code Online (Sandbox Code Playgroud)

这个工程很大的dropbox.com,但其他网站如google.com,facebook.com等只需加载登录页面或给出错误(google.com给出了一个错误,说我需要启用Cookie).

现在我只是手工发布帖子数据; 查看站点的登录表单,并在我的代码中将名称/值字段放在postData中.在像google这样的网站上,登录表单有很多隐藏字段,我也一直在将它们添加到postData中.

如果有人能让我知道我做错了什么,请告诉我,我对此非常困惑.

an0*_*00b 15

尝试替换"utf-8"(在第二个参数中)"BASE64".


小智 11

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    WebView webView = new WebView(this);

    setContentView(webView);

    String url = "http://example.com/somepage.php";
    String postData = "postvar=value&postvar2=value2";

    webView.postUrl(url, EncodingUtils.getBytes(postData, "base64"));
}
Run Code Online (Sandbox Code Playgroud)

  • 我在Android [HERE]中阅读了EncodingUtils.java的源代码(http://grepcode.com/file/repo1.maven.org/maven2/org.apache.httpcomponents/httpcore/4.4/org/apache/http/util /EncodingUtils.java#95)`EncodingUtils.getBytes(postData,"base64")`与`postData.getBytes()`相同.只需使用`postData.getBytes()`而不是EncodingUtils.(如果您需要迁移到没有EncodingUtils的Android M(API 23)) (13认同)