【问题标题】:File is not uploded after removing System.out.println("response :: " + conn.getResponseMessage());删除 System.out.println("response :: " + conn.getResponseMessage()); 后文件未上传
【发布时间】:2013-05-29 16:47:04
【问题描述】:

以下是我上传文件 GCS 的功能:

public void fileUpload(InputStream streamData, String fileName,
            String content_type) throws Exception {

    byte[] utf8Bytes = fileName.getBytes("UTF8");
    fileName = new String(utf8Bytes, "UTF8");
    URL url = new URL("http://bucketname.storage.googleapis.com"+"/"+"foldername/"+fileName);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("PUT");
    conn.setRequestProperty("Accept", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Authorization", "OAuth " + GcsToken.getAccessToken());
    conn.setRequestProperty("x-goog-meta-FileName", fileName);
    conn.setRequestProperty("x-goog-meta-ContentType", content_type);

    OutputStream os = conn.getOutputStream();

    BufferedInputStream bfis = new BufferedInputStream(streamData);
    byte[] buffer = new byte[1024];
    int bufferLength = 0;

    // now, read through the input buffer and write the contents to the file

    while ((bufferLength = bfis.read(buffer)) > 0) {
        os.write(buffer, 0, bufferLength);

    }

    System.out.println("response :: " + conn.getResponseMessage());// ?????

}

此代码可以正常上传文件,但是 删除最后一个 Sysout 后,它没有上传文件 System.out.println("响应::" + conn.getResponseMessage());

这背后的原因是什么?

有什么帮助吗?

感谢

【问题讨论】:

    标签: java httpurlconnection google-cloud-storage httpconnection


    【解决方案1】:

    您需要关闭您的 OutputStream 以表明您已经完成了请求正文的编写:

    os.close();
    

    您还应该检查请求的响应代码:

    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
        // Error handling code here.
    }
    

    它之前工作的原因是因为getResponseMessage 函数阻塞,直到请求完成发送并收到回复。如果不检查响应值,您的函数就会退出,并且 HTTP 请求可能未完成发送。

    【讨论】:

      【解决方案2】:

      感谢您的澄清。 我已经尝试过 os.close() 也尝试过 os.flush()。但同样的问题。 :(

      我终于更新了我的代码:

              while ((bufferLength = bfis.read(buffer)) > 0) {
                  os.write(buffer, 0, bufferLength);
      
              }
              os.close();
              if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                  //logger
              } 
      

      现在我可以上传文件了。

      再次感谢。

      【讨论】:

        猜你喜欢
        • 2015-01-06
        • 2023-04-01
        • 2012-04-06
        • 1970-01-01
        • 2012-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多