BlobstoreService.getUploads always returns NULL - java

I'm trying to store an image to the Google Appengine Blobstore from an android device. What I've done so far:
Created an Enpoint (Google Cloud Endpoints) that returns an upload URL (Working)
Created a POST request with OKHTTP3 that sends the image file in a multipartform (Working? Maybe not?)
Created a Servlet that is passed to the upload URL to handle getting the keys. (It gets called, but getUpload always returns null.)
I'm thinking maybe it has to do with how I'm sending my POST request?
OkHttpClient client = new OkHttpClient();
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"photo\""),
RequestBody.create(MediaType.parse("image/jpeg"), file)
)
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
In my Servlet I can see a param named "photo" but calling:
List<BlobKey> blobs = blobstoreService.getUploads(req).get("photo");
returns null. Zero BlobKeys...
I'm sure I'm missing something dumb... Any help would be incredibly appreciated!

So in the end it WAS the POST request.
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormData("photo", "photoname")
.addFormData("photo", "photo.jpg", RequestBody.create(MediaType.parse("image/jpeg"), file)
.build();

Related

How to upload a file with a presigned URL to an object storage minio with a Java client Api?

I want to upload a file to an object storage minio which created a presigned URL using a Java client API.
In the documentation only refers to creating presigned URL or creating some. Is there a to upload using the presigned url.
I think you probably got the answer by now, gonna put it here for others who might have stumbled upon similar task.
There are a few different HTTP clients that you could use in JAVA, so implementations may vary. The idea is, once you get the URL, it is just a matter of sending an HTTP PUT request using the URL with the file's binary content, just like you would do in any file upload procedure. As far as I know, you cannot send multipart file data directly using PUT, you have to send binary stream.
Here's an example of uploading a jpeg file with OkHttpClient:
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("image/jpeg");
RequestBody body = RequestBody.create(mediaType, "<file contents here>");
Request request = new Request.Builder()
.url("<minio presigned url here>")
.method("PUT", body)
.addHeader("Content-Type", "image/jpeg")
.build();
Response response = client.newCall(request).execute();
Another example with Spring's RestTemplate where the incoming request to the controller is a MultipartFile. If it's a File object instead, you can use your favorite utility method such as byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file) to get a byte array from that file.
HttpHeaders headers = new HttpHeaders();
HttpEntity<byte[]> entity = new HttpEntity<>(multipartFile.getBytes(), headers);
restTemplate.exchange(new URI("<presignedUrl>"),
org.springframework.http.HttpMethod.PUT, entity, Void.class);
You can search for your specific HTTP Client, just need to look for "RESTful file upload with PUT request" Or something similar.

MindSphere URL Access

I am trying to access Mindsphere URL with Java Code. I am getting 403 forbidden error while doing it. While I am able to hit other POST URL's for other sites, Mindsphere URL is getting blocked by same piece of Java Code. Can someone help?
What am i missing in my Code?
restTemplate.exchange(,,*,TimeseriesData.class) is line giving error
MindSphere demands a authorization header with a JWT Token, if you call directly the API. I guess you have an Developer account in MindSphere. Try Application credentials in the Developer cockpit. With that credentials you can get a bearer token with an oauth flow.
If not just ping me again.
See Exampel with OK HTTP
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials");
Request request = new Request.Builder()
.url("https://questdev.piam.eu1.mindsphere.io/oauth/token")
.post(body)
.addHeader("Accept", "application/json")
.addHeader("cache-control", "no-cache,no-cache")
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addHeader("Postman-Token", "24126d6b-3461-48fb-9060-6fd005804227")
.build();
Response response = client.newCall(request).execute();

Okhttp big file upload fails

I am experiencing an issue with Okhttp + Node.js Formidable serverside big file upload.
Currently the upload works for < 100Mb files but fails for bigger files.
For bigger files, the onprogress event serverside is fired until 99% progress, regardless of the file size, then it stops, reports request abort, and the onfile event is not fired.
Already tried timeouts workarounds, even defined a custom SocketFactory to manually set the socket keepalive and sotimeout.
So, Im stuck here. Any help would be appreciated.
CustomSocketFactory MySocketFactory = new CustomSocketFactory();
OkHttpClient client = new OkHttpClient.Builder()
.socketFactory(MySocketFactory)
.readTimeout(largenumber, TimeUnit.SECONDS)
.writeTimeout(largenumber, TimeUnit.SECONDS)
.connectTimeout(largenumber, TimeUnit.SECONDS)
.build();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("nombre_file", file_pais.getName())
.addFormDataPart("nombre_pais", pais.getName())
.addFormDataPart("file", file_pais.getName(),
RequestBody.create(MediaType.parse("application/octet-stream"),
new File(filepath)
.build();
Request request = new Request.Builder()
.url(server_url)
.post(requestBody)
.build();
Call call = client.newCall(request);
Response response = call.execute();
response.body().close();
Its way too easy using snoopy api: one line of code if you exclude identifiers definition :)
URI uri = ...;
Path fileToUpload = ...;
Snoopy.builder()
.config(SnoopyConfig.defaults())
.build()
.post(uri)
.followRedirects(true)
.failIfNotSuccessfulResponse(true)
.body(fileToUpload)
.consumeAsString();
https://bitbucket.org/abuwandi/snoopy
Tested on large files and it worked like a charm

Passing Multiple URL's for OKhttp url Request type

Is there any way to Passing Multiple URL's for OKhttp url Request type. Actually i want pass multi url's like website, mobile request urls(Androd, mobile browser, tablet)
Request request = new Request.Builder()
.url("multi url" + ---
.addheader(---).build();
No
The OkHttp Request object allows one and only one URL.
If you require several requests, create different requests:
Request stackoverflowRequest = new Request.Builder()
.url("https://www.stackoverflow.com/")
.addHeader(...)
.build();
Request googleRequest= new Request.Builder()
.url("https://www.google.com/")
.addHeader(...)
.build();
If you don't want to write all the headers X times, you can use the following:
Request templateRequest = new Request.Builder()
.url("https://www.example.com/")
.addHeader(...)
.build();
Request stackoverflowRequest = templateRequest.newBuilder()
.url("https://www.stackoverflow.com/")
.build();
Request googleRequest = templateRequest.newBuilder()
.url("https://www.google.com/")
.build();

OPTIONS/HEAD REST API request with Okhttp3

I`m writing some Rest client on Android and I met a problem - I have no idea how to make HEAD and OPTIONS requests.
There are no problems with GET/POST/PUT/DELETE/PATCH requests in OkHttp3, basically they looks like:
request = new Request.Builder()
.url(url)
.headers(headerBuilder.build())
.post(bodyBuilder.build())
.build();
And OkHttp3 doesnt provide additional methods like head() or option().
So how can I make HEAD and OPTIONS requests using OkHttp3?
Found answer, may be it will be useful for someone else
OkHttp3 still has method
Builder method(String method, RequestBody body)
So OPTIONS requests looks like
Request request = new Request.Builder()
.url(url)
.headers(headerBuilder.build())
.method("OPTIONS",requestBody)
.build();
same for HEAD
It appears (at least in the current implementation, API 3.12.0), HEAD request can be made just like GET and others:
Request request = new Request.Builder()
.url(url)
.head()
.build();
OPTION still has to be implemented using .method()

Categories

Resources