我正在尝试使用 java 登录到报告系统。到目前为止,我已经尝试了许多使用 HttpURLConnection 的不同实现。我要发布的 HTML 归结为:
<form name="logonForm" method="POST" action="http://remoteserver/logon.object">
<input type="hidden" name="qryStr" value="">
<input type="hidden" name="cmsVisible" value="true">
<input type="hidden" name="authenticationVisible" value="true">
<input type="hidden" name="referer" value="">
<input type="hidden" name="refererFormData" value="">
<input type="hidden" name="isFromLogonPage" value="true">
<input type="text" name="cms" value="xxxxx" class="textfield" id="apsTextEdit">
<input type="text" name="username" value="xxxxx"class="textfield" id="usernameTextEdit">
<input type="text" name="password" value="xxxxx"class="textfield" id="passwordTextEdit">
<select name="authType"id="authenticationSelectBox">
<option selected value='xxxxx'>xxxxx</select>
<input type="submit" name="SUBMIT">
</form>
我知道此表单提供了有效输入,因为当我在浏览器中单击“提交”时,它会将我登录到我的报告系统。但是,当我发送编程请求时,我总是会得到上面的 html 作为响应。请注意,我已经尝试了大约一百万个使用 HttpURLRequest 的实现。一个例子:
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(parameters);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
String allLines = "";
while ((line = rd.readLine()) != null) {
allLines += "\n" + line; // Process line...
}
wr.close();
rd.close();
return allLines;
其中“参数”的范围从无到我发布的 HTML 中的每个 URL 编码参数,并且连接(目前,就像我尝试过其他配置一样)设置如下:
connection = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(true);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setAllowUserInteraction(false);
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded; charset=" + "UTF-8");
connection.setUseCaches(false);
connection.connect();
我知道细节有点稀疏,所以如果您需要更多信息,请告诉我,非常感谢您提供的任何信息!
最佳答案
你需要确保你也参加了name=value
对所有 <input type="hidden">
元素和一个<input type="submit">
你想在查询字符串中以编程方式“按下”。该按钮只有一个名称,但无论如何,您都需要传递它。这样服务器端就可以区分是否按下了一个按钮,如果按下了,是哪个按钮。
此外,如果表单需要 session (它可能使用基于请求的 token ),那么您还需要自己维护 cookie。检查并获取 Set-Cookie
从第一个响应的标题并将其设置为 Cookie
后续请求的 header 。
为了更简单、更简洁的 HTTP/表单处理,请考虑 Apache HttpComponents Client .
另请参阅:
关于java - POST 似乎不适用于我的 HttpURLConnection 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3093340/