我正在尝试使用jsoup登录网站(https://dashboard.ngrok.com/user/login)。我对GET请求没有任何问题,但是当我尝试使用凭据执行POST请求时,我会收到提示:
HTTP错误提取URL。状态= 400
我尝试使用连接进行POST请求时发送的相同参数为请求设置更好的标头。
Connection.Response loginForm = Jsoup.connect(url)
.method(Connection.Method.GET).execute();
System.out.println("GET");
Document document = Jsoup.connect(url)
.data("email", usr)
.data("password", psw)
.header("Host", "dashboard.ngrok.com")
.header("Origin", "https://dashboard.ngrok.com")
.referrer(url)
.cookies(loginForm.cookies())
.post();
我也尝试过这种类型的请求:
Response res = Jsoup.connect(url)
.data("email", usr, "password", psw)
.method(Method.POST)
.execute();
Map<String, String> loginCookies = res.cookies();
Document doc = Jsoup.connect(ngrok)
.cookies(loginCookies)
.get();
输出显示:
线程“ main”中的异常org.jsoup.HttpStatusException:提取URL的HTTP错误。状态= 400,URL = https://dashboard.ngrok.com/user/login
答案 0 :(得分:0)
根据TDG的建议,我添加了csrf_token。 结果代码是这样的:
CookieHandler.setDefault(new CookieManager());
Connection.Response loginForm = Jsoup.connect(url)
.method(Connection.Method.GET)
.userAgent(USER_AGENT).execute();
Document tok = loginForm.parse();
Element e = tok.select("input[name=csrf_token]").first();
String appToken = e.attr("value");
System.out.println(appToken);
Connection.Response login = Jsoup.connect(url)
.data("email", usr)
.data("password", psw)
.data("csrf_token", appToken)
.userAgent(USER_AGENT)
.header("Host", "dashboard.ngrok.com")
.header("Origin", "https://dashboard.ngrok.com")
.referrer(url)
.cookies(loginForm.cookies())
.method(Method.POST)
.execute();
谢谢您的帮助。