form-data request, with okHttp3 - java

I'm trying to make a request where I pass some parameters in the Body, as shown in the image.
Example Image
Example:
Key: file[], Value: "xml", Content-Type: application/xml Key: query, Value: {"boxe/File": false}, Content-Type: application/xml
I'm getting a Bad Request error, I think my code isn't right. Follow how it is being done
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file[]", xml, RequestBody.create(null, "application/xml"))
.addFormDataPart("query", "{\"boxe/File\": false}", RequestBody.create(null, "application/xml"))
.build();
Request request = new Request.Builder().url(endPoint).addHeader("x-integration-key", integrationKey)
.addHeader("Authorization", "Bearer " + token)
.post(requestBody).build();

Managed to solve it, the order of the parameters were wrong,
follow the correct order
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file[]","", RequestBody.create(MediaType.parse("application/xml"), xml))
.addFormDataPart("query", "", RequestBody.create(MediaType.parse("application/json"), boxFileJson))
.build();

Related

okhttp3 passing parameter with "--data {json}"

How can I pass parameter with "--data {json}" on okHttp3? Do I need to add it in the headers like below? Or its not on the header, it need to be on another object?
Request request = new Request.Builder()
.header("Content-Type", "application/json; charset=utf-8")
.addHeader("data", "{json}")
.url(url)
Please let me know.
You must add to RequestBody :
final String BOUNDARY = String.valueOf(System.currentTimeMillis());
RequestBody requestBody = new MultipartBody.Builder(BOUNDARY)
.setType(MultipartBody.FORM)
.addFormDataPart("data", JsonData)
//.addFormDataPart("otherPara", otherPara)
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();

AWS Chime: How to sign an HTTP Request for Create Meeting API in spring boot?

I didn't find any useful way to generate the Signature V4 in java for signing an AWS Chime HttpRequest. I want to use 3 apis of Aws Chime (Create meeting, create attendee and delete meeting) inside my java code.
Can anyone help me please !
API Details:
Url: https://service.chime.aws.amazon.com/meetings
Body: { "ClientRequestToken": "AXEXAMPLE", "MediaRegion":
"us-east-2" }
Headers: "content-type", "application/json" "host",
"service.chime.aws.amazon.com" "x-amz-date", "20200526T094404Z"
"authorization", ?(Generated Signature)
API Key: JHDCHGEXAEXAMPLE Secret Key : 4sjfkkjffs/sfkkh/sfkj/example
private Response createMeeting() {
OkHttpClient client = new OkHttpClient();
Response response = null;
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\n\t\"ClientRequestToken\": \"AXEXAMPLE\",\n \"MediaRegion\": \"us-east-2\"\n}");
Request request = new Request.Builder()
.url("https://service.chime.aws.amazon.com/meetings")
.post(body)
.addHeader("content-type", "application/json")
.addHeader("host", "service.chime.aws.amazon.com")
.addHeader("content-length", "68")
.addHeader("x-amz-date", getIsoDate())
.addHeader("authorization", "?????????") //To be replaced by generated signature
.addHeader("cache-control", "no-cache")
.build();
try {
response = client.newCall(request).execute();
System.out.println("ResponseMessage===========> " + response.message());
} catch (IOException e) {
System.out.println("Error===========> " + e.getMessage());
}
return response;
}
The error I am getting is: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.

When sending okhttp request: HTTP ERROR 405 and invalid_client

I'm making a request to a website. However, I keep getting a returned JSON of {"error":"invalid_client"}. Additionally, when I navigate to the URL I'm making the request to through a web browser it shows HTTP ERROR 405.
From what I read on those errors that might mean that my request isn't structured correctly.
According to the API's documentation, this is an example of the request type I'm trying to do:
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "client_secret={your_client_secret}&client_id={your_client_id}&code={your_authorization_code}&grant_type=authorization_code&redirect_uri={your_redirect_uri}");
Request request = new Request.Builder()
.url("https://api.website.com/v2/oauth2/token")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("cache-control", "no-cache")
.build();
Response response = client.newCall(request).execute();
From what I can tell mine should be doing the same thing, just a little differently.
Here is a Pastebin of my doInBackground method (I'm using AsynchTask). Here is the more applicable part:
OkHttpClient client = new OkHttpClient();
// A section here gets strings from a JSON file storing values such as client_id
RequestBody bodyBuilder = new FormBody.Builder()
.add("client_secret", CLIENT_SECRET)
.add("client_id", CLIENT_ID)
.add("code", AUTHORIZATION_CODE)
.add("grant_type", GRANT_TYPE)
.add("redirect_uri", REDIRECT_URI)
.build();
System.out.println("Built body: " + bodyBuilder.toString());
String mediaTypeString = "application/x-www-form-urlencoded";
MediaType mediaType = MediaType.parse(mediaTypeString);
RequestBody body = RequestBody.create(mediaType, requestbodyToString(bodyBuilder)); // See Edit 1
Request request = new Request.Builder()
.url(TARGET_URL)
.post(body)
.addHeader("content-type", mediaTypeString)
.addHeader("cache-control", "no-cache")
.build();
try {
System.out.println("Starting request.");
Response response = client.newCall(request).execute();
String targetUrl = request.url().toString() + bodyToString(request);
System.out.println("request: " + targetUrl);
String responseBodyString = response.body().string();
System.out.println("response: " + responseBodyString);
return responseBodyString;
} catch (IOException ex) {
System.out.println(ex);
}
Like I said, I keep getting a returned JSON of {"error":"invalid_client"}, and when I navigate to the URL I'm making the request to through a web browser it shows HTTP ERROR 405.
I'd love to provide as much additional information as you need. Thanks!
Edit 1: The second parameter of this used to be "bodyBuilder.toString()", but I changed it because I realized it wasn't actually sending the body. The result is still the same - {"error":"invalid_client"}. The method now used comes from here.
I figured out what it was - I hadn't actually been writing the authentication_code to the file, only adding it to another JSONObject. Oops. :)

How to make an Okhttp Request with "Content-type:application/x-www-form-urlencoded"?

I have an api requirement of Sending following parameters in header-
Content-Type - application/x-www-form-urlencoded
authKey- (Session token)
and following parameters in body(form day i.e key-value pair)
storeId -1
type -Product
CategoryId -324
But whenever I hit this api, I am always getting 401(UnAuthorized) error.
I have tried using MultipartRequest body and formBody, I know this is nothing to do with the body(Its the header where I need to send the Content-Type and authKey). Below is my code-
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.addHeader("Content-Type", "application/x-www-form-urlencoded");
requestBuilder.addHeader("authKey",AppSharedPref.getTokenMobikul(context));
RequestBody formbody = new FormBody.Builder().add("CategoryId",bodyparms.get(0)).
add("type",bodyparms.get(1)).build();
requestBuilder.post(formbody);
The Same api is giving Response with retrofit library So how to achieve this using Okhttp.
Might this will help
FormBody.Builder formBuilder = new FormBody.Builder()
.add("key", "value");
// add more parameter as follow:
formBuilder.add("mobile", "9999999999");
RequestBody formBody = formBuilder.build();
Request request = new Request.Builder()
.url("https://www.hittheserver.com")
.post(formBody)
.build();

Setting HTTP headers on RESTeasy requests with attachments

I'm using RESTeasy 3.x to submit a REST request with an attachment to a third party service. They've asked that the request have the following headers set:
Accept: application/json
Content-Disposition: attachment; filename="attamentFilename"
Content-Type: application/octet-stream
My first attempt was simply to add the headers as I've seen done with Authorization header like this:
protected Response getResponse(final String url, final String filename, final InputStream attachment) {
ResteasyWebTarget target = resteasyClient.target(url);
MultipartFormDataOutput output = new MultipartFormDataOutput();
output.addFormData("attachment", attachment, MediaType.APPLICATION_OCTET_STREAM_TYPE);
Response response = target.request()
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_TYPE)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filename + "\"")
.post(Entity.entity(output, MediaType.MULTIPART_FORM_DATA));
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
return response;
}
But, when I debugged from the server side the headers weren't being set as expected. I also tried a ClientRequestFilter, but again the headers weren't quite what I needed.
I've managed to get something close to what I need by using addFormData like this:
protected Response getResponse(final String url, final String filename, final InputStream attachment) {
ResteasyWebTarget target = resteasyClient.target(url);
MultipartFormDataOutput output = new MultipartFormDataOutput();
output.addFormData("attachment", attachment, MediaType.APPLICATION_OCTET_STREAM_TYPE, filename);
Response response = target.request()
.post(Entity.entity(output, MediaType.MULTIPART_FORM_DATA));
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
return response;
}
This produces two of the three headers I need:
Content-Disposition: form-data; name="attachment"; filename="attamentFilename"
Content-Type: application/octet-stream
I'm assuming MultipartFormDataOutput is discarding the headers I try to set and building its own, and that I can't use the .header method for all types of requests. Does this sound right?

Categories