setFixedLengthStreamingMode不适用于对s3的http PUT请求

时间:2018-06-25 17:32:53

标签: java connection httpurlconnection

我正在尝试使用HttpURLConnection对s3 URL进行http PUT请求。 但是由于某种原因,setFixedLengthStreamingMode对我不起作用。有人可以帮忙吗?

HttpURLConnection connection = (HttpURLConnection) new URL(uploadLocation).openConnection();
connection.setRequestProperty("x-amz-server-side-encryption", CommonConstants.AMZ_SERVER_SIDE_ENCRYPTION);
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
connection.setFixedLengthStreamingMode((int) new File(localFilePath).length());

最后一条语句什么也不做。如果我执行connection.getContentLength(),则显示-1。有人可以帮忙吗?

编辑: 我实际上正在尝试执行此操作:但这不起作用。出现Java io异常:流已关闭。

    BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
    FileInputStream input = new FileInputStream(localFilePath);
    int length;
    while ((length = input.read(buffer)) > 0) {
      out.write(buffer, 0, length);
    }
    input.close();
    out.close();

2 个答案:

答案 0 :(得分:1)

请勿将BufferedOutputStreamsetFixedLengthStreamingMode一起使用,因为在固定长度模式下,必须在请求之前将所有主体写入输出流。并且缓冲可能会阻止它。

要修复代码,您可以直接写入OutputStream out = connection.getOutputStream();。或者只是不打setFixedLengthStreamingMode

答案 1 :(得分:0)

HttpURLConnection.getContentLength()返回响应的长度,而不是请求的长度。