如何使用android中的jsoup自动登录网页?

时间:2016-04-04 12:13:34

标签: java android android-studio jsoup

我尝试使用jsoup为我的用户自动登录http://www.bvrit.edu.in并使用webview显示我的用户的登录网页。我添加了jsoup API,使用了检查元素检查了id usename字段是txtId1,密码是txtPwd1,并用相应的名称替换post中的数据。我还为清单添加了互联网访问权限,但我无法显示网页,我的代码如下所示,我想我得到了一些基础错误,但无法弄清楚。

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState)  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void main(String[] args) throws IOException {

    WebView browser = (WebView) findViewById(R.id.bvritWebview);

    Connection.Response loginForm = Jsoup.connect("http://www.bvrit.edu.in/")
            .ignoreContentType(true)
            .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")
            .referrer("http://www.google.com")
            .timeout(12000)
            .followRedirects(true)
            .method(Connection.Method.GET)
            .execute();

    Connection.Response loginFormFilled = Jsoup.connect("http://www.bvrit.edu.in/")
            .ignoreContentType(true)
            .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")
            .followRedirects(true)
            .referrer("https://login.to/")
            .data("txtId1", "username")//check the form to find field name for user name
            .data("txtPwd1", "password")//check the form to find field name for user password
            .cookies(loginForm.cookies())
            .method(Connection.Method.POST)
            .execute();
    int statusCode = loginFormFilled.statusCode();
    Map<String, String> cookies = loginFormFilled.cookies();
    browser.getSettings().setJavaScriptEnabled(true);
    browser.loadUrl("http://www.bvrit.edu.in");

}

}

登录后的网络标题部分 - enter image description here

1 个答案:

答案 0 :(得分:1)

You are missing few parameters in your POST request. Load the page in your browser, press F12 to launch the developer tools and look at the POST request. You will see something like this -
POST request

You must send all these parameters to the server, not just those you do send now.
The first 3 parameters are unique to each session, and you can get them form the first GET request, something like this (the CSS selector may be different, I didn't try it on your URL):

Document doc = loginForm.parse();
Element e = doc.select("input[id=__VIEWSTATE]").first();
String viewState = e.attr("value");