我有一个命令行:
curl -u username:passwd -k "https://myserver/a/b/c"
当我在Ubuntu或Cygwin下调用它时,我会得到正确的信息。
现在我愿意用Java完成它。所以我有这样的Java代码:
public class Test {
public static String auth = "username:passwd";
public static String url = "https:/myserver/a/b/c";
public static void main(String[] args) {
try {
URL url = new URL(url);
final byte[] authBytes = auth.getBytes(StandardCharsets.UTF_8);
String encoding = java.util.Base64.getEncoder().encodeToString(authBytes);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", encoding);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
但它似乎不起作用并始终返回HTTP响应代码411。 java代码有问题吗?
先谢谢。
答案 0 :(得分:1)
HTTP响应代码411表示“服务器拒绝接受没有定义内容长度的请求。”
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
HttpsUrlConnection
应该可以为你做到这一点。查看setFixedLengthStreamingMode()
。我想你还需要setDoOutput()
。