gpt4 book ai didi

java - 使用Java登录后解析HTML源

转载 作者:行者123 更新时间:2023-11-30 04:58:24 25 4
gpt4 key购买 nike

我一直在尝试访问一个网站来解析我正在开发的 Android 应用程序的数据,但登录时运气不佳。

网站是https://giffgaff.com/mobile/login

下面是该页面中表单的精简版本 (HTML):

<form action="/mobile/login" method="post">
<input type="hidden" name="login_security_token" value="b22155c7259f402f8e005a771c460670">
<input type="hidden" name="redirect" value="/mobile">
<input type="hidden" name="p_next_page" value="">


<input name="nickname" maxlength="25" type="text" value="" />
<input name="password" type="password" value="" />

<button name="step" type="submit" value="Login">Login</button>
</form>

谁能建议我如何使用 Java 登录该网站然后解析重定向的页面?

到目前为止,我已经尝试过以下流程:

public static void main(Context context) {
try {
// Construct data
String data = URLEncoder.encode("nickname", "UTF-8") + "=" + URLEncoder.encode("testingA", "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode("testing", "UTF-8");

// Send data
URL url = new URL("https://giffgaff.com/mobile/login");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();

// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str = "";
String line;
while ((line = rd.readLine()) != null) {
str += line;
}

AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Output");
alertDialog.setMessage(str);
alertDialog.setButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

}
});
alertDialog.show();

wr.close();
rd.close();
} catch (Exception e) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("ERROR");
alertDialog.setMessage(e.toString());
alertDialog.setButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

}
});

alertDialog.show();
}
}

但是我的尝试返回页面,就好像登录信息不正确一样。

如果您想亲自了解登录页面的行为方式,这里有一些测试登录详细信息:昵称(用户名):testingA密码:测试该网站似乎还依赖于名为“napaSessionId”的 Cookie

最佳答案

首先请注意,如果您没有直接许可执行此操作,请注意,相关网站可能会在其服务条款中排除此操作。

要回答这个问题,网站拒绝登录的原因有很多很多。为了成功地做到这一点,您需要尽可能接近浏览器处理事务的方式。为此,您需要了解真正的浏览器正在做什么。

https 更加棘手,因为许多 http 嗅探器无法处理它,但 httpwatch 声称可以。检查 HTTP 事务,然后尝试复制它们。

您的 url.openConnection() 调用实际上将返回一个 HTTPURLConnction 实例,转换为该实例,然后您将能够轻松设置各种 http header ,例如 User-Agent。

最后一点,您说可能需要 cookie。您的代码不会处理 cookie。为此,您需要使用 cookie 管理器,例如:http://download.oracle.com/javase/tutorial/networking/cookies/index.html

关于java - 使用Java登录后解析HTML源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7741694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com