JAX-RS retrieve Entity parameter from post Response java - java

I am trying to retrieve entities from body response of a POST request
Client client = ClientBuilder.newClient(new ClientConfig());
Response response = client.target(url)
.request(MediaType.APPLICATION_JSON)
.post(Entity.entity(form,MediaType.APPLICATION_JSON), Response.class);
Log.trackingResponse(url, response);`
request is 200 OK, parameters I want to retrieve exist, I can see them while debugging:
My problem is I can not access these parameters.
I tried the following solution but it was not successful:
Map<String, Object> jsonResponse = clientResponse.readEntity(Map.class);
MessageBodyProviderNotFoundException
Order order = response.readEntity(Order.class);
Order being a custom class with Jacksonannotation, MessageBodyProviderNotFoundException
String jsonResponse = clientResponse.readEntity(String.class);
returns < ! DOCTYPE html PUBLIC ....
the whote html code, but not my parameters
My maven has the correc jackson depedency.
Any idea ?
Thanks

These parameters are part of the request you sent, not the response.
They are members of the form you sent in the request entity:
.post(Entity.entity(form,MediaType.APPLICATION_JSON), Response.class);

Related

how to send the data in request body as json to resttemplate.exchange

Assume I am getting the values from one API, need to send that data to other API through resttemplate.exchange
I am iterating the values like below
String Data="";
for(String value: receivedvalues){
Data=Data.concat(","+val)
}
List<map> result=resttemplate.exchange(url+Data,HttpMethod.GET,ArrayList.class).getBody);
The above problem is I'm adding data to request url, but i need to send through the request body but in this case how we can send data through the resttemplate.exchange.Can any one have any idea on this.
Thanks in advance.
Map your JSON object to POJO class and then use RestTemplate.exchange(...) method.
Usage example:
ReceivedValuesClass receivedValuesPojo = mapJson(receivedValues);
RequestEntity request = RequestEntity
.get(new URI(url))
.accept(MediaType.APPLICATION_JSON)
.body(receivedValuesPojo);
ResponseClass result=resttemplate.exchange(url,HttpMethod.GET,ResponseClass.class).getBody;
More information here: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#exchange-org.springframework.http.RequestEntity-java.lang.Class-

What is the difference between UniRest and Spring RestTemplate giving an http 400 Bad Request?

What is the difference with UniRest and Spring RestTemplate which is giving back a 400 Bad Request with apparently the same header and body sent ?
I try to reach the HubSpot API to create a BlogPost, but using RestTemplate I have a 400 Bad Request error, and using UniRest works alright (returns an OK response). However, I do not want to include a library just to make one REST call: I'd rather stick to RestTemplate.
The request data I need to send
HttpMethod: POST
URL: https://api.hubapi.com/content/api/v2/blog-posts?hapikey=*****************
Header: Content-Type: application/json
Body: (represented by a class instance as blogpostSendPost further down)
{
"name": "My first API blog post!",
"content_group_id": 351076997
}
Using RestTemplate
Setting up the request:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<BlogpostSendPost> request = new HttpEntity<>(blogpostSendPost, headers);
log(request.toString());
//LOG PRINT: <BlogpostSendPost(name=My first API blog post!, content_group_id=351076997),[Content-Type:"application/json"]>
OR in JSON
The .json() method converts my object in Json like you can see in the logs
HttpEntity<String> request = new HttpEntity<>(blogpostSendPost.toJson(), headers);
log(request.toString());
//LOG PRINT: <{"name":"My first API blog post!","content_group_id":"351076997"},[Content-Type:"application/json"]>
With .postForObject(): 400 Bad Request
BlogpostResponsePost answer = restTemplate.postForObject(
"https://api.hubapi.com/content/api/v2/blog-posts?hapikey=***********",
request,
BlogpostResponsePost.class);
With .exchange(): 400 Bad Request
BlogpostResponsePost answer = restTemplate.exchange(
"https://api.hubapi.com/content/api/v2/blog-posts?hapikey=**********",
HttpMethod.POST,
request,
BlogpostResponsePost.class);
Using UniRest: OK
HttpResponse<JsonNode> resp = Unirest
.post("https://api.hubapi.com/content/api/v2/blog-posts?hapikey=**********")
.header("Content-Type", "application/json")
.body(blogpostSendPost)
.asJson();
I am using PostMan to call my REST SpringBoot Application which is using theses Services : when I am calling the HubSpot API directly from PostMan it works fine, just like with UniRest lib.
Thanks for your help guys !!
Please refer https://community.hubspot.com/t5/APIs-Integrations/Getting-400-Bad-Request-when-trying-to-add-a-Blog-Post/td-p/306532
Instead of converting request object to json, pass request object directly. It worked for me.
// TRY 1: CONTACTS - RestTemplate - OK - contact is created (API V1)
HttpEntity request1 = new HttpEntity<>(contactSendList, headers);
ContactResponseInformations answer1 = restTemplate
.postForObject(
HubSpotConfiguration.URL_CREATE_CONTACT,
request1,
ContactResponseInformations.class);
log.info(answer1.toString()); // OK

Spring Boot MultiValueMap parameters in Postman

I have implemented OAuth2 in Spring boot. It works well when testing it in JUnit but I always get unauthorized when I try the API in postman.
test function in JUnit:
private String obtainAccessToken(String username, String password) throws Exception {
final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", "password");
params.add("client_id", CLIENT_ID);
params.add("username", username);
params.add("password", password);
ResultActions result = mockMvc.perform(post("/oauth/token")
.params(params)
.with(httpBasic(CLIENT_ID, CLIENT_SECRET))
.accept(CONTENT_TYPE))
.andExpect(status().isOk())
.andExpect(content().contentType(CONTENT_TYPE));
String resultString = result.andReturn().getResponse().getContentAsString();
JacksonJsonParser jsonParser = new JacksonJsonParser();
return jsonParser.parseMap(resultString).get("access_token").toString();
}
I tried following APIs in postman:
POST type http://localhost:8080/oauth/token with content type application/json
in Body section I selected raw and JSON :
{
"grant_type":"password",
"client_id":"clientIdPassword",
"username":"a",
"password":"a"
}
It showed 401 Unauthorized. Then I also tried like this :
Post type with content type application/json, http://localhost:8080/oauth/token?grant_type=password&client_id=clientIdPassword&username=a&password=a. This also showed 401 Unauthorized.
My question is how can I set MultiValueMap as parameter in Postman?
you should use authorization tab of postman to send auth headers along with request body however you like.
PFA sample image
When you send the request via POSTMAN tool, select the type of HTTP method (POST, PUT, DELETE), then select the "raw" option in "Body" tab and then just add the JSON of the Map in it. Make sure you have selected "Content-type" as "application/json" in "Headers" .

jersey client get error message body

I am using the following code to consume a rest post service
Client client = ClientBuilder.newClient();
WebTarget target = client.target("wrong url");
Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON);
Response response = builder.post(Entity.entity(param, MediaType.APPLICATION_JSON), Response.class);
As expected I am getting error. and status code 400 Bad Request. But i am not getting the error message. when i run response.getStatusInfo() i get bad request but my server sends additional info.
when i call this using postman i get error info in the Body window.
So how do I get this error body info from the response object?
or any other way???
You get the response body as usual with Response#readEntity:
Read the message entity input stream as an instance of specified Java type using a MessageBodyReader that supports mapping the message entity stream onto the requested type.
Example:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("wrong url");
Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON);
Response response = builder.post(Entity.entity(param, MediaType.APPLICATION_JSON), Response.class);
String body = response.readEntity(String.class);
With Response#getStatusInfo you get only HTTP status, class and reason phrase.
I am new to Jersey and JAX-RS, but I believe this question is equivalent to Handling custom error response in JAX-RS 2.0 client library, which has much better answers.

Getting header values, Status code etc from Jax-Rs Response class in Junit

I am using Restful web Service using Dropwizard. And generating response as:
Response response = resources.client().resource("/url")
.header("CONTENT-TYPE","value")
.post(Response.class, jsonRequestString);
Now I want to write unit test to ensure the returned content type is corrected in Response Object. how to do that?
You can use the ClientResponse type in Jackson. For example, using a GET operation:
ClientResponse response = Client.create()
.resource(url)
.get(ClientResponse.class);
String contentType = response.getHeaders()
.getFirst("Content-Type");
System.out.println(contentType);

Categories

Resources