这是我的代码:
public static String sendPostRequest(String url) {
StringBuffer sb = null;
try {
String data = URLEncoder.encode("user", "UTF-8") + "="
+ URLEncoder.encode("username", "UTF-8") + "&"
+ URLEncoder.encode("password", "UTF-8") + "="
+ URLEncoder.encode("password", "UTF-8");
System.out.println(data); //Just to check if data is correct
URL requestUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) requestUrl
.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
DataOutputStream osw = new DataOutputStream(conn.getOutputStream());
osw.writeBytes(data);
osw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String in = "";
sb = new StringBuffer();
while ((in = br.readLine()) != null) {
sb.append(in + "\n");
}
osw.close();
br.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
但是每当我尝试通过此 http post 请求登录时,它都会返回始终位于该网站页面上的 html 代码,而不是包含我的用户页面的特定 html 代码。 html 登录表单如下所示:
<td width="100" align="left"><span class="texte_listing_bold">Login:</span></td>
<td width="300" align="center"><input class="form_size1" type="text" name="user"></td>
</tr>
<tr>
<td width="100" align="left"><span class="texte_listing_bold">Password:</span></td>
<td width="300" align="center"><input class="form_size1" type="password" name="password"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="hidden" name="login_action" value="true">
<input class="bouton_nosize" type="submit" value="Login">
</td>
通常,按钮具有名称元素,我也可以通过我的代码调用这些元素,这确实有效并允许我登录到这样的网站,但由于某种原因这不起作用。这是什么原因?
最佳答案
此登录表单使用名为 login_action
的隐藏输入字段,其值为 true
。
您需要在请求中传递该信息以及用户名和密码。
只需确保您已提供所有必需的信息即可。 您可以使用 HTTP 嗅探器检查浏览器发送的内容,但最好是查看您尝试进行身份验证的页面的来源。
如果您无法访问或控制 Web 服务器登录页面源代码,那么您可能不应该首先编写此代码。身份验证机制将来可能会发生变化,并且针对脚本(例如您尝试编写的脚本)可能存在许多安全限制,因为通常不接受允许机器人登录用户页面和网络抓取内容。
关于java - 无法将 HTTP Post 请求发送到登录表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9957120/