2
votes

I am trying to upload a CSV file into google cloud storage using CloseableHttpClient.getting response as 200 but content type is not properly reflected.

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);

Please find the below uploaded Google storage bucket Screenshot:

enter image description here

1
Did you try adding the Content-Type header as well ?soufrk
@soufrk Yes i tried, it did not workElango Mani
Is there any particular reason for trying to upload files that way? If not, I would use Google Cloud Storage client libraries for Java. Here's the documentation for uploading object and the GitHubIñigo
@Iñigo I thought, if we use HttpClient then it will easy to migrate if we are moving to other cloud storage with just an API change.Elango Mani

1 Answers

1
votes

Following what we were commenting, you will need to change your code either way. Every cloud storage provider have a very different way to upload files, just think about the authorisation process, you'll need to change that for sure.

Not only the fact that the code will need to be changed, using the provided libraries will be a more optimal way. If you are run it the code in an GCP product (let's say GAE), it will use internal network, so it will be way faster. Even if it's not the case, the routing of the libraries will be better, as they are though to do that. In general, as good practise, using cloud provider libraries is the way to go.

For you to have an easier way to switch between cloud providers, I would create a particular function to upload files, and call it from your main function. This way you would only need to change that function.

Again, here it's the documentation needed as I sent in previous comments [1], [2] and [3]