为什么下面的代码打印“Method:GET”而不是“Method:POST”?将POST请求视为GET请求
我需要它以编程方式授权http://www.havenandhearth.com/portal/。
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("http://www.havenandhearth.com/portal/sec/login");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
String parameters = "username=xxx&password=yyy";
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(parameters.length()));
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(parameters);
wr.flush();
wr.close();
int responsecode = conn.getResponseCode();
if (responsecode != HttpURLConnection.HTTP_OK) {
System.out.println("Unable to make POST request. Response code: " + responsecode);
return;
}
System.out.println("Method: " + conn.getRequestMethod());
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
}
如果我将URL更改为http://httpbin.org/post,它按预期工作。
为了实现目标,您需要将xxx和yyy替换为实际的帐户凭据。
在此先感谢。
当我运行你的代码,我看到这个结果:'方法:POST' –
@David Herrero啊,这是因为无效的帐户凭据,对不起 – FrozenHeart
好吧,我认为,当您使用您的凭据成功的POST,网页将您重定向到主页,所以conn现在发出GET请求。 –