I'm trying to implement REST client for Google Drive with Jersey 2.0.
According to following document, I made the code that sends files by multipart request.
https://developers.google.com/drive/v2/reference/files/insert
https://developers.google.com/drive/manage-uploads
String targetUrl = "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart&access_token=" + token.access_token;
WebTarget target = client.target(targetUrl);
final FileDataBodyPart filePart = new FileDataBodyPart("file", file);
final MultiPart multipart = new FormDataMultiPart().field("title", file.getName())
.field("description", file.getName())
.bodyPart(filePart);
Response response = target.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(multipart, multipart.getMediaType()));
System.out.println("response:" + response.readEntity(String.class));
Here's the POST request by the code.
POST /upload/drive/v2/files?uploadType=multipart&access_token={ACCESS_TOKEN} HTTP/1.1\r\n
Accept: application/json\r\n
Content-Type: multipart/form-data; boundary=Boundary_1_1833261898_1373877178038\r\n
User-Agent: Jersey/2.0 (HttpUrlConnection 1.7.0_25)\r\n
MIME-Version: 1.0\r\n
Host: www.googleapis.com\r\n
Content-Length: 42430\r\n
MIME Multipart Media Encapsulation, Type: multipart/form-data, Boundary: "Boundary_1_1833261898_1373877178038"
Type: multipart/form-data
First boundary: --Boundary_1_1833261898_1373877178038\r\n
Encapsulated multipart part: (text/plain)
Content-Type: text/plain\r\n
Content-Disposition: form-data; name="title"\r\n\r\n
Line-based text data: text/plain
Boundary: \r\n--Boundary_1_1833261898_1373877178038\r\n
Encapsulated multipart part: (text/plain)
Content-Type: text/plain\r\n
Content-Disposition: form-data; name="description"\r\n\r\n
Line-based text data: text/plain
Boundary: \r\n--Boundary_1_1833261898_1373877178038\r\n
Encapsulated multipart part: (text/plain)
Content-Type: text/plain\r\n
Content-Disposition: form-data; filename="GoogleDrive.txt"; modification-date="Fri, 12 Jul 2013 08:15:47 GMT"; size=41918; name="file"\r\n\r\n
Line-based text data: text/plain
Last boundary: \r\n--Boundary_1_1833261898_1373877178038--\r\n
My post request was sent but following error occurred.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
Please tell me how to avoid this error.
An upload request should have two multi-parts: metadata and file content and metadata part should be in JSON.
In your case you create a new form-encoded part for each attribute. Use the reference on docs to see the proper formatting: https://developers.google.com/drive/manage-uploads#multipart
final MultiPart multipart = new FormDataMultiPart().field("title", file.getName())
.field("description", file.getName())
.bodyPart(filePart);
Your multipart body should be valid JSON.
Related
I want to parse a multipart/mixed web response I'm getting in to proper content,
--Boundary_33046_835445861_1627668603035
Content-Type: application/json
Content-Disposition: form-data; name="contentAnalyzerResponse"
{"cpf:inputs":{"documentIn":{"cpf:location":"InputFile0","dc:format":"application/pdf"},"params":{"cpf:inline":{"elementsToExtract":["text","tables"],"renditionsToExtract":["tables","figures"]}}},"cpf:engine":{"repo:assetId":"urn:aaid:cpf:58af6e2c-1f0c-400d-9188-078000185695"},"cpf:status":{"completed":true,"type":"","status":200},"cpf:outputs":{"elementsRenditions":[{"cpf:location":"fileoutpart0","dc:format":"image/png"},{"cpf:location":"fileoutpart1","dc:format":"image/png"},{"cpf:location":"fileoutpart2","dc:format":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},{"cpf:location":"fileoutpart3","dc:format":"image/png"},{"cpf:location":"fileoutpart4","dc:format":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},{"cpf:location":"fileoutpart5","dc:format":"image/png"},{"cpf:location":"fileoutpart6","dc:format":"image/png"},{"cpf:location":"fileoutpart7","dc:format":"image/png"},{"cpf:location":"fileoutpart8","dc:format":"image/png"},{"cpf:location":"fileoutpart9","dc:format":"image/png"},{"cpf:location":"fileoutpart10","dc:format":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},{"cpf:location":"fileoutpart11","dc:format":"image/png"},{"cpf:location":"fileoutpart12","dc:format":"application/vnd.
--Boundary_33046_835445861_1627668603035
Content-Type: application/octet-stream
Content-Disposition: form-data; name="fileoutpart92"
�PNG
��L���S�|��wp���F��k�^����{��{�d\'�����|v������Q<H=||�϶�7����yHBz��q���o݉մ�\:���/�[Ó���:�� ����Tկ�����K�/|g��HY��F�����/��ݳ/�7�6�w$������F��sZ�0T�I��p���0�힍��:�J�����_��>���k��9~���C�P��Pl3���K\�:�ʵ����?z��G�w�V��_yg/�������~Z_3��W����x�[���N�9U}�E�~|�g��:�u��m�B��ZQ����z�O��=W�=gܪ�|x�2����o|pU��/���~�����ޒ������}����}�W���v���k��pM�yI��I<�t�w��
���}~�����M<����7~�c�l���gF��?���o�!` ��0�G�ioG.ީ������^��S�96Ź��a8K�{�N�paa8�<�1���p�]؝�>�x�#Y�z���y�����w>s�K���c�5��pQ�b����i���3�8���������&�h>?wo���{���WjɅO݉�T�w���8��:�ut�̩�Eu����&^���>sʸmk<������1
��oB"�0� �������ƾ��ܴ�a8c�u�~��<%0
The response I'm getting is similar to the responses above and I want to get the individual content from the response.
I have a POST method that needs to support both multipart/form-data and application/json.
i.e. consumes = { MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_JSON_VALUE }
When I'm supporting Multipart request, I need a multipart file and a multipart json which can be obtained by declaring as below:
Line 1-> #RequestPart("file") MultipartFile file, #RequestPart("jsonString") InputJsonVO inputJsonVO
Similarly when supporting an application/json, I need to accept the whole body as a Json content:
Line 2 -> #RequestBody InputJsonVO inputJsonVO
It works fine when we have either line 1 or line 2, but not both in the same method as parameters.
`#PostMapping(path = "/multipart", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE,
MediaType.APPLICATION_JSON_VALUE })
public String getMessage(#RequestPart(required=false, name="file") MultipartFile file, #RequestPart(required=false, name="jsonString") InputJsonVO inputJsonVO,
#RequestBody(required=false) InputJsonVO inputJsonVO2
)`
With this method declaration if I send a POST request:
POST /multipart HTTP/1.1
Host: localhost:8080
content-type: application/json
Content-Length: 335
<A Valid Json>
This works fine.
But when I sent a POST request as below from postman, it doesn't work:
POST /multipart HTTP/1.1
Host: localhost:8080
Content-Length: 650
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="/C:/Users/sdamarla/Downloads/J867FE94.jpeg"
Content-Type: image/jpeg
(data)
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="jsonString"
Content-Type: application/json
<A valid Json>
----WebKitFormBoundary7MA4YWxkTrZu0gW
Gives below error:
Content type 'multipart/form-data;boundary=--------------------------335202067624768397899751' not supported]
Note: multipart request is working fine when removing the #RequestBody and the corresponding parameter.
Please let me know if this is a valid use case and if so where am I failing.
Just define two different methods, one for each representation:
#PostMapping(path = "/multipart", consumes = MediaType.APPLICATION_JSON_VALUE)
public String getMessage(#RequestBody InputJsonVO inputJsonVO) {
getMessage(null, inputJsonVO);
}
#PostMapping(path = "/multipart", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String getMessage(#RequestPart MultipartFile file, #RequestPart InputJsonVO inputJsonVO) {
// your code here
}
when i am trying to upload the image in the web application using POST method of HTTP using Jmeter ,Its throwing error as below
Sampler Request:
Size in bytes: 436
Headers size in bytes: 335
Body size in bytes: 101
Sample Count: 1
Error Count: 1
Data type ("text"|"bin"|""): text
Response code: 405
Response message: Method Not Allowed
Response headers:
HTTP/1.1 405 Method Not Allowed
Allow: GET, HEAD, OPTIONS, TRACE
Content-Length: 101
Content-Type: text/html
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=a1634f39ccba9517317254d32be7078bb62c2877a947d85cab990f2708382045;Path=/;Domain=revflexsit.azurewebsites.net
Date: Tue, 28 Jun 2016 10:04:41 GMT
HTTPSampleResult fields:
ContentType: text/html
DataEncoding: null
Request:
POST http://revflexsit.azurewebsites.net/#//testerprofile
POST data:
--8WPDqrXY5glD81_9CcLHn-xfOTrWvH4Dh4srjx
Content-Disposition: form-data; name="profileUploadPhoto"; filename="Tulips.jpg"
Content-Type: image/jpeg
Content-Transfer-Encoding: binary
<actual file content, not shown here>
--8WPDqrXY5glD81_9CcLHn-xfOTrWvH4Dh4srjx--
[no cookies]
Request Headers:
Connection: keep-alive
Content-Length: 621121
Content-Type: multipart/form-data; boundary=8WPDqrXY5glD81_9CcLHn-xfOTrWvH4Dh4srjx; charset=US-ASCII
Host: revflexsit.azurewebsites.net
User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_40)
Response Data:
The page you are looking for cannot be displayed because an invalid method (HTTP verb) is being used.
The server response is pretty much self-explanatory, you're not allowed to make POST requests to that URL, only GET, HEAD, OPTION and TRACE ones.
Why just not to record your test scenario using HTTP(S) Test Script Recorder and modify the resulting test "skeleton" as required?
If you are still eager to build your scenario manually,looking into the http://revflexsit.azurewebsites.net/ site, it seems correct request will look something like:
Path: /api/TesterProfile/UploadTesterProfile?Id=${YOUR_ID_HERE}&UpdateAdminId=0&dimensions=x,y,x,y
Files Upload:
File Path: full path to image, you're trying to upload
Parameter Name: profileUploadPhoto
MIME Type: relevant photo MIME Type
Don't forget to tick "Use multipart/form-data for POST" box.
See How to Test Image Upload Functionality With JMeter for more detailed explanation.
I am attempting to upload a file with additional parameters using RequestParts. I have the file uploading correctly; however, when I try and add in the additional parameters I get an error in response.
My Controller:
#RequestMapping(value = "/v1/cases/{caseId}/file", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
#ResponseStatus(HttpStatus.OK)
#ResponseBody
public Success uploadFile(
#RequestPart(value="file") MultipartFile file,
#RequestPart(value="fileParameters") FileParameters fileParameters) throws FileNotFoundException, IOException {
I have tried to POST to this 2 different ways with different errors:
1)
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="file"; filename="myFile"
Content-Type:
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="fileParameters"
{"filePassword":"testPassword", "configuration":{}, "target":null}
----WebKitFormBoundaryE19zNvXGzXaLvS5C
this errors with:
The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method. See 'supportedMediaTypes' in 'additionalInfo' for a list of supported types
2)
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="file"; filename="myFile"
Content-Type:
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="fileParamters[filePassword]"
testPassword
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="fileParamters[configuration]"
{}
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="fileParamters[target]"
null
----WebKitFormBoundaryE19zNvXGzXaLvS5C
which returns the following error:
"rootExceptionClass": "org.springframework.web.multipart.support.MissingServletRequestPartException",
"rootExceptionMessage": "Required request part 'keyParameters' is not present."
I'm assuming the first approach is the correct one; however, the application does support JSON, so I'm not sure what I am missing configuration wise. Is there something I have to add to the request for this to work correctly, or am I missing something in a message converter.
Note: Not sure this matters but I am using Postman to test the endpoint.
add
Content-Type: application/json;
under the line of
Content-Disposition: form-data; name="fileParameters"
to explicit how to resolve your parameters
see spring docs here
I have met the same issue with you! I changed the #RequestPart to #Multipart, the issue was fixed. hope it can help for you!
How do you send a RESTLET POST request without the optional parameter "; CHARSET=UTF-8" in the HTTP header?
When I use WGET in UNIX to try this proof of concept for my service, I can specify the optional Content-type: ... in the HTTP header like this:
Specifying the encoding as UTF-8:
wget --header="Content-Type: application/x-www-form-urlencoded; charset=UTF-8" --post-file=input_file.xml https://localhost/myservice
Omitting the encoding:
wget --header="Content-Type: application/x-www-form-urlencoded" --post-file=input_file.xml https://localhost/myservice
When I do something like this in RESTLET
Form form = new Form();
String accessToken = "Moroni123";
form.set("access_token", accessToken);
If I do this to see the representation:
Representation rep = form.getWebRepresentation();
I see this using the rep.toString() method:
[application/x-www-form-urlencoded,UTF-8]
Is there a way I can get it to look like this? SoapUI sends it without "UTF-8", how can I do this in RESTLET?
[application/x-www-form-urlencoded]
In fact, this hint corresponds to the character set within the Restlet representation. You can simply set it to null with the method setCharacterSet on the representation and you won't have anymore the UTF-8 in the header Content-Type. The following code describes this:
Form form = new Form();
String accessToken = "Moroni123";
form.set("access_token", accessToken);
Representation repr = form.getWebRepresentation();
MediaType mediaType = repr.getMediaType();
// corresponds to application/x-www-form-urlencoded
CharacterSet characterSet = repr.getCharacterSet();
// corresponds to UTF-8
rep.setCharacterSet(null);
ClientResource cr = new ClientResource("http://...");
cr.post(repr);
We will have the following request:
POST / HTTP/1.1
Date: Thu, 19 Feb 2015 15:58:06 GMT
Content-Type: application/x-www-form-urlencoded
Accept: */*
User-Agent: Restlet-Framework/2.3.0
Cache-Control: no-cache
Pragma: no-cache
Host: 127.0.0.1:8181
Connection: keep-alive
Content-Length: 22
access_token=Moroni123
Without this, the content of the header Content-type is:
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Hope it helps,
Thierry