【问题标题】:how to use HttpsUrlConnection in java如何在java中使用HttpsUrlConnection
【发布时间】:2016-03-28 06:12:35
【问题描述】:

我有一个命令行:

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代码有问题吗?

提前致谢。

【问题讨论】:

  • 您正在执行 POST 但未发送任何内容。这就是curl 所做的吗?否则,您就是在比较苹果和橙子。
  • curl 命令生成一个 GET...

标签: java authentication curl https


【解决方案1】:

HTTP 响应代码 411 表示“服务器拒绝接受没有定义 Content-Length 的请求。”

http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

HttpsUrlConnection 应该能够为您做到这一点。查看setFixedLengthStreamingMode()。我想你还需要setDoOutput()

【讨论】:

  • 非常感谢。我愿意添加 setDoOutput(true)setFixedLengthStreamingMode (int contentLength) 。但我不知道热设置参数contentLength。我给了它一些随机值,然后得到了IOException: insufficient data written。我也累了setChunkedStreamingMode,但还是不能工作。
  • 你要设置成你写的数据的长度,也就是零。
猜你喜欢
  • 2011-03-03
  • 2011-10-02
  • 2010-10-31
  • 2022-07-18
  • 2017-05-29
  • 2015-01-20
  • 1970-01-01
  • 2014-12-26
  • 1970-01-01
相关资源
最近更新 更多