java - 如何在android中使用jsoup自动登录网页?

标签 java android android-studio jsoup

我试图让我的用户自动登录 http://www.bvrit.edu.in使用 jsoup 并使用 webview 为我的用户显示登录的网页。我添加了 jsoup API,使用检查元素检查用户名字段的 id 为 txtId1,密码为 txtPwd1,并将帖子中的数据替换为相应的名称。我还添加了互联网访问权限来 list ,但我无法显示网页,我的代码如下所示,我认为我犯了一些基础知识错误,但无法弄清楚。

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

}

}

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

最佳答案

您的 POST 请求中缺少一些参数。在浏览器中加载页面,按 F12 启动开发人员工具并查看 POST 请求。你会看到这样的东西 -
POST request

您必须将所有这些参数发送到服务器,而不仅仅是您现在发送的参数。
前 3 个参数对于每个 session 都是唯一的,您可以从第一个 GET 请求中获取它们,如下所示(CSS 选择器可能不同,我没有在您的 URL 上尝试):

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

关于java - 如何在android中使用jsoup自动登录网页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36402328/

相关文章:

android - android studio:如何从junit 3更改为junit 4

java - 我应该如何将这些数据存储在 Java 枚举中?

Java 多进程和堆大小

java - 让 Jedis 与 JMeter 引擎一起工作

android - JNI : Passing multiple parameters in the function signature for GetMethodID

java - 格式化我的系统后未安装应用程序且未签署应用程序

java - hibernate 自动发现并生成 POJO 的数据库映射

java - 如何在android中旋转 Canvas 上的可绘制对象

android - 在 Android 中与 Map 一起旋转 onTouch 事件

macos - OSX 10.10.1 上的文件系统区分大小写不匹配(Android Studio 和 IntelliJIDEA)