Converting RestTemplate exchange to okHttpClient call - java

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

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

CloseableHttpClient with BasicAuth creds returning 400 error. With same BasicAuth creds OkHttp3 client works well

I have the sample code snippet. It is returning 400 error. With same BasicAuth creds using OkHttp3 client works well. What is missing here?
```
String BASIC_AUTHORIZAION = "Basic *********"; // masked
String reportRequest = "{***}"; //json string
CloseableHttpClient client = HttpClientBuilder.create().build();
FormBodyPart bodyPart = FormBodyPartBuilder
.create()
.setName("ReportRequest")
.setBody(new StringBody(reportRequest, ContentType.APPLICATION_JSON))
.build();
HttpEntity requestEntity = MultipartEntityBuilder
.create()
.addPart(bodyPart)
.addTextBody("type", ContentType.APPLICATION_JSON.toString())
.build();
HttpUriRequest httpPost = RequestBuilder
.post(MPG_MESSAGE_STATUS_REPORT_URL)
.addHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString())
.addHeader("Authorization", BASIC_AUTHORIZAION)
.setEntity(requestEntity)
.build();
HttpResponse response = client.execute(httpPost);
Resolved as it does not need the line to add header for Content-Type MULTIPART_FORM_DATA:
.addHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString())

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

Spring Boot multipart content type HTTP Request using RestTemplate

I am trying to emulate this request using RestTemplate in Spring Boot
curl -X POST
'https://my.craftar.net/api/v0/image/?api_key=123456789abcdefghijk123456789abcdefghijk'
-F "item=/api/v0/item/4fe672886ec142f6ab6d72d54acf046f/"
-F "file=#back_cover.png"
Here's my code:
MultiValueMap<String, Object> params= new LinkedMultiValueMap<>();
params.add("item", "/api/v0/item/4fe672886ec142f6ab6d72d54acf046f/");
final String filename=file.getOriginalFilename();
Resource contentsAsResource = new ByteArrayResource(file.getBytes()){
#Override
public String getFilename(){
return filename;
}
};
HttpHeaders imageHeaders = new HttpHeaders();
imageHeaders.setContentType(MediaType.IMAGE_PNG);
HttpEntity<Resource> imageEntity = new HttpEntity<Resource>(contentsAsResource, imageHeaders);
params.add("file", imageEntity);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.ALL));
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String,Object>> requestEntity =new HttpEntity<>(params,headers);
try {
ResponseEntity<String> responseEntity = restTemplate.exchange(url,HttpMethod.POST, requestEntity, String.class);
return responseEntity.getBody();
} catch (final HttpClientErrorException httpClientErrorException) {
return httpClientErrorException.getResponseBodyAsString();
} catch (Exception exception) {
return exception.getMessage();
}
The above request throws a HttpClientErrorException and this what the response body looks like
{"error": {"message": "Expected multipart/form-data; boundary=<..> content but got multipart/form-data;boundary=x6G0xWVxdZX4n8pYNU8ihGAnCg4Twj3DgMARYDs.", "code": "WRONG_CONTENT_TYPE"}}
I have also tried using FileSystemResource, but it throws the same exception. The problem probably lies in formatting the data in multipart content-type.
If it can help, this is the code template generated by Postman on a successful request using Okhttp.
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
RequestBody body = RequestBody.create(mediaType,
"------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n
Content-Disposition: form-data; name=\"item\"\r\n\r\n/api/v0/item/3d8dcdd1daa54bcfafd8d1c6a58249b5/\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n
Content-Disposition: form-data; name=\"file\"; filename=\"times_logo.png\"\r\nContent-Type: image/png\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--");
Request request = new Request.Builder()
.url("https://my.craftar.net/api/v0/image/?api_key=c6d4750c7368806fab27294fba8d0f93d48e1e11")
.post(body)
.addHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
.addHeader("cache-control", "no-cache")
.addHeader("Postman-Token", "cf09a989-338e-4d68-8968-b30a43384e5f")
.build();
Response response = client.newCall(request).execute();
just add the Resource to params instead of creating a HttpEntity
params.add("file", contentsAsResource);

Retrieve a cookie using Spring RestTemplate

I need to get a cookie from a server using Spring RestTemplate. Do you guys know how I can perform this?
Thank you for your help!
final String url = "http://codeflex.co:8080/rest/Management/login";
RestTemplate template = new RestTemplate();
Credentials cred = new Credentials();
cred.setUserName("admin#codeflex.co");
cred.setPassword("godmode");
HttpEntity<Credentials> request = new HttpEntity<>(cred);
HttpEntity<String> response = template.exchange(url, HttpMethod.POST, request, String.class);
HttpHeaders headers = response.getHeaders();
String set_cookie = headers.getFirst(HttpHeaders.SET_COOKIE);
code from the example
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Cookie", "JSESSIONID=" + session.getValue());
HttpEntity requestEntity = new HttpEntity(null, requestHeaders);
ResponseEntity rssResponse = restTemplate.exchange(
"https://jira.example.com/sr/jira.issueviews:searchrequest-xml/18107/SearchRequest-18107.xml?tempMax=1000",
HttpMethod.GET,
requestEntity,
Rss.class);
Rss rss = rssResponse.getBody();
from http://springinpractice.com/2012/04/08/sending-cookies-with-resttemplate

Categories