如何使用 JSON API 和 CloseableHttpClient 将文件上传到 Google Cloud Storage 存储桶?

how to upload a file into Google Cloud Storage bucket using JSON API and CloseableHttpClient?

我正在尝试使用 CloseableHttpClient.getting 响应 200 将 CSV 文件上传到 google 云存储,但内容类型未正确反映。

CloseableHttpClient httpClient = HttpClients.createDefault();
 CloseableHttpResponse response;
 try {
     ContentBody  fileBody = new FileBody(content, ContentType.DEFAULT_BINARY);
     HttpEntity entity = MultipartEntityBuilder.create().addPart("FILE_NAME", fileBody)
                        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE).build();
     HttpPost request = new HttpPost(
                        "https://www.googleapis.com/upload/storage/v1/b/BUCKET_NAME/o?uploadType=media&name=FILE_NAME");
     request.addHeader(Constants.API_HEADER_AUTHORIAZATION,
                        Constants.API_HEADER_AUTHORIAZATION_VALUE + accessToken());
     request.setEntity(entity);
     response = httpClient.execute(request);

请找到下面上传的Google存储桶截图:

根据我们的评论,您将需要以任何一种方式更改您的代码。每个云存储提供商都有非常不同的文件上传方式,只需考虑授权过程,您肯定需要更改它。

不仅需要更改代码,使用提供的库将是一种更优化的方式。如果您 运行 它是 GCP 产品(比方说 GAE)中的代码,它将使用内部网络,因此速度会更快。即使不是这种情况,库的路由也会更好,因为它们就是这样做的。一般来说,作为一种良好的做法,使用云提供商库是可行的方法。

为了让您更轻松地在云提供商之间切换,我会创建一个特定的函数来上传文件,并从您的主函数调用它。这样你只需要改变那个功能。

同样,这是我在之前的评论中发送的所需文档 [1], [2] and [3]