gpt4 book ai didi

java - 删除 System.out.println ("response::"+ connection.getResponseMessage()) 后文件未上传;

转载 作者:太空宇宙 更新时间:2023-11-04 07:36:21 25 4
gpt4 key购买 nike

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

这背后的原因是什么?

有什么帮助吗?

谢谢

最佳答案

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

os.close();

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

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

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

关于java - 删除 System.out.println ("response::"+ connection.getResponseMessage()) 后文件未上传;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16819666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com