1

以下是我的功能来上传文件GCS:删除System.out.println(“response ::”+ conn.getResponseMessage())后,文件不会升级;

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(“响应::” + conn.getResponseMessage());

这是什么原因?

有帮助吗?

thnaks

回答

1

您需要关闭的OutputStream,以表明您写完请求体:

os.close(); 

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

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

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

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 
     } 

现在我可以上传文件

再次感谢