删除System.out.println后,文件未上传(“response ::”+ conn.getResponseMessage());

时间:2013-05-29 16:47:05

标签: java httpurlconnection google-cloud-storage httpconnection

以下是我上传文件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());// ?????

}

此代码适用于uplaod文件,但是 删除最后一个Sysout后,它不会上传文件 System.out.println(“response ::”+ conn.getResponseMessage());

这背后的原因是什么?

任何帮助?

thnaks

2 个答案:

答案 0 :(得分:1)

您需要关闭OutputStream以指示您已完成编写请求正文:

os.close();

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

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

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

答案 1 :(得分:0)

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

最后我更新了我的代码:

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

        }
        os.close();
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            //logger
        } 

现在我可以上传文件了。

再次感谢。