下面是我的代码,它执行 POST 请求来登录网站。当我运行相同的命令时,我收到的消息响应为 411。任何人都可以帮助我设置正确的内容长度吗?
try {
String request = "http://<domain.com>/login";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestProperty("Content-Length", "1");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("email", "abc");
connection.setRequestProperty("password", "xyz");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
int code = connection.getResponseCode();
System.out.println("Response Code of the object is " +code);
if(code == 200)
System.out.println("OK");
connection.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
最佳答案
好的 - 您没有将任何内容移动到请求正文中,因此您应该将长度设置为“0”。
添加:
连接.connect();
之后:
connection.setRequestMethod("POST");
google“httpurlconnection post 参数”,用于向 POST 请求添加参数。该网站至少有四五个解决方案。
关于java - java中的HTTP POST请求 - 设置内容长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26247555/