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

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

Related

how to get session cookie from server and set it into the api header?

There is cookie header in my api request, every time I have to copy this cookie from postman and paste in my code to make it work. how can I generate cookie in my app and give that value in cookie header?
this is my login code:
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("username","zee#earthonetechno.com")
.addFormDataPart("password","E1234567")
.build();
Request request = new Request.Builder()
.url("192.168.1.51/auth/login")
.method("POST", body)
.addHeader("User-Agent", "Koala Admin")
.addHeader("Content-Type", "application/json")
.addHeader("Cookie", "session=3e3710cb-9b41-47ea-ab1b-a1e1801e188b")
.build();
Response response = client.newCall(request).execute();
I want to put the cookie here in addHeader("Cookie", "session=3e3710cb-9b41-47ea-ab1b-a1e1801e188b")
I am developing in android studio
I found the solution for this
just include these lines in login part to get cookie
Headers allHeaders = response.headers();
headerValue = allHeaders.get("Set-Cookie");
and use this headerValue for subsequent api calls

Converting RestTemplate exchange to okHttpClient call

I am trying to replace ResteTemplate in a spring boot application with OkHttpClient.
Here is my code with the RestTemplate from Spring:
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", "application/json");
headers.add("Content-Type", "application/x-www-form-urlencoded");
HttpEntity<?> httpEntity = new HttpEntity<>("grant_type=client_credentials&scope=" + config.getScope(), headers);
ResponseEntity<Token> resp = getRestTemplate(builder).exchange(
new URI(config.getTokenUrl()),
HttpMethod.POST,
httpEntity,
Token.class);
And here is my attempt to map that code with OkHttpClient:
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("body", "grant_type=client_credentials&scope=" + config.getScope())
.build();
Request request = new Request.Builder()
.header("Accept", "application/json")
.header("Content-Type", "application/x-www-form-urlencoded")
.url("http://" + config.getTokenUrl())
.post(requestBody)
.build();
OkHttpClient client = buildOkHttpClient();
Response response = client.newCall(request).execute();
Objects.requireNonNull(response.body()).close();
The problem is that I get an error Response{protocol=http/1.1, code=405, message=Method Not Allowed.
The Http Method is POST as seen in the RestTemplate.
But I am not sure how should I map/transform the HttpEntity<?> httpEntity = new HttpEntity<>("grant_type=client_credentials&scope=" + config.getScope(), headers); to conform to OkHttp?
Maybe the mistake is here?
Any help is appreciated!
Check this link and this construction:
RequestBody requestBody = new FormBody.Builder()
.add("grant_type", "client_credentials")
.add("scope", config.getScope())
.build();
Request request = new Request.Builder()
.url("http://" + config.getTokenUrl())
.post(requestBody)
.build();

Make a post request with okHttp

I make a post request using okHttp with the next code:
final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, params);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = null;
response = client.newCall(request).execute();
The server response with:
response
{
message: {
user: {
id: 12,
name: 'myName'
},
message: 'Usuario creado con éxito.',
code: 200
}
}
But the response that okHttp gives me is:
Response{protocol=http/1.1, code=200, message=OK, url=http://localhost:2222/api/users}
There isn´t a way to get what the server sends me with okHttp?
If the response is sent in the body you can get it with:
response.body().string();
You just had to look on the documentation
¡Salud!
What you are getting is the header of response object. you can access the body of response by:
response.body().string();
full code:
final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, params);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = null;
response = client.newCall(request).execute();
String responseBody = response.body().string();

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. :)

OKHTTP Post FormDataMultiPart

I need your help, i'd like to know if there is a way to post a FormDataMultiPart with okHttp.
I know you're gonna say that there already are responses.
This is my case :
// Resource
#Consume(FORMDATAMULTIPART)
public Response getMultiPart(FormDataMultiPart multipart) {
return response.ok(service.postMultiPart(multipart);
}
// Service
public void postMultiPart(FormDataMultiPart multiPart) {
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder() {
.url(URL)
.post(multiPart)
}
I know that post only get RequestBody and this is my question, do you know guys a way to convert the FormDataMultiPart to RequestBody??
Thanks a lot
In the Service change this part of the code
final Request request = new Request.Builder() {
.url(URL)
.post(multiPart)
to (assuming i'm sending a file) and use RequestBuilder
File file; // This is the file I want to send.
MediaType mediaType = MediaType.parse("multipart/form-data");
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("key", "name", RequestBody.create(mediaType, file)).build();
okhttp3.Request.Builder requestBuilder = new okhttp3.Request.Builder()
.headers(headerBuild)
.url(url);
requestBuilder.post(requestBody);
okhttp3.Request request = requestBuilder.build();
Have a look at MediaType which has been added in the above code.

Categories