I'm trying to use one api that in the response body we have this structure:
{"flag": false,
"codes":[
"a3f2b9ddf8886b04993632"]}
At Postman, and executing a curl, the response is exactly this one.
But when I use restTemplate.exchange(...) to return the response body,it's always returning for codes: [[object Object]]
UriComponentsBuilder builder = UriComponentsBuilder.fromUri(URL...); //cannot show partner's url here
header.add("Accept", MediaType.APPLICATION_JSON_VALUE);
header.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
ResponseEntity<String> resourceHttpEntity = restTemplate.exchange(
builder.toUriString(),
HttpMethod.GET,
new HttpEntity<>(header), String.class); //header also has an authorization bearer token that is in another class
System.out.println(resourceHttpEntity.getBody());
Response body from this:
{"flag":false,"codes":["[object Object]"]}
I saw some examples that this occurs, but in Javascript, and we use JSON.stringfy to solve it.
But at Java we don't have this option. I don't know if is a miss-configuration or something.
Even I try to get this response body with the class model using String[], ArrayList for this property. Tried to convert in String.class, JSonNode.class, and it's returning this way.
I tried to use objectMapper to convert, and even test with HTTPURLConnection to confirm and it's happening the same thing. I have the same result.
Any suggestions?
If you need to print the content of a generic object in Json format you can print it as follow:
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
System.out.println(ow.writeValueAsString(object));
// Or better log.info(ow.writeValueAsString(object);
If you don't need to format your output you can call directly writeValueAsString on the objectMapper:
Method that can be used to serialize any Java value as a String
System.out.println(new ObjectMapper().writeValueAsString(object));
Updated answer after the update on the question.
It seems that the remote service that you are invoking is returning exactly the body that you showed in the updated answer.
Your code is treating the body as a simple string, so there is no manipulation on the client-side (your code). It means that is possible that for particular values the server-side (the web service that you are invoking) is performing some strange operation (probably a bean to json conversion) that will generate this output.
You have many ways to check it:
make the same call using postman
make the same call using curl
add a sniffer between your client and the server and use it to log the passing data
For the first two alternatives you have to be sure to use exactly the same data used by the java code. And execute them from the same machine (may be that a proxy can change the behaviour of the call).
We discover that the RestTemplate #Bean that we already have in code, was causing this issue. So I just instantiate a new RestTemplate from scratch, and the issue was resolved.
Thank you for your time.
Create Java class with below attributes and use as response entity type.
Public class Response{
boolean flag;
List<String> codes;
}
ResponseEntity<Response> resourceHttpEntity =
restTemplate.exchange(
builder.toUriString(),
HttpMethod.GET,
new HttpEntity<>(header), Response.class);
Related
In my java play framework project (2.3 version) I need to call an exposed endpoint from outside also from inside my project. To be more specific, in another controller.
So in my routes I have this mapping:
POST /evaluation/budgetamout #bank.controller.EvaluationController.evaluateBudgetAmount()
The controller EvaluationController contains a methods named as evaluateBudgetAmount:
public Result evaluateBudgetAmount() {
ApiResponse response = new ApiResponse();
JsonNode jsonNode = request().body().asJson();
String result = // performe evaluations and save it into database passing jsonNode
response.addData(result);
return ok(response);
So in another controller with a specific method named as checkFinalResult I need to perform the call evaluateBudgetAmount giving a new input in the request(a new json in the post request), but I have no idea to figure out.
Surery I do not want to use the Promise to performed a new call inside my project that need to pass through from outside, to be clearer this approach is not admissible:
F.Promise<WSResponse> rProm = WS.url(pathUrl).post(info);
There is another way?
I need to call another api and I am trying to use postForEntity as below:
restTemplate.postForEntity(postUrl, request, responseType)
Now, the api that I am calling is returning an object of a particular type, let's say CustomerDto. But I am not interested in this object. I just want to post and I don't want anything in return so I don't want to create this CustomerDto class in my application. So, for this scenario, in the above statement, what should i replace for responseType. In case, I had wanted the returned object, I would have given CustomerDto.class in case of responseType, but I dont want anything in return, so what do I do?
You can use postForLocation instead of postForEntity.
restTemplate.postForLocation(postUrl, request)
Another way is to use Void.class as response-type
i am trying to make a client for services exposed through REST.I have multiple number of classes extending a single class.
Now when i send the request and get a response,every time i need to type cast the response for specific class.i am trying to automate this process,can this be achieved at run time?
I am thinking of using generics and reflection but unable to move forward.what i exactly want to achieve is by just mentioning a unique string or say request,i must be able to get exact same response without type casting it with that particular response class.
By using generics i succeeded in reducing some code for typecasting,still i am not satisfied as i want to completely achieve it at run time.
RequestClass request=(RequestClass)getRequest(some attributes);
output=(Responseclass)response.getResult();
Here every time i need to mention the request and response classes,i don't want to do this.
can i do something where i can map the request and response classes to a key or a string and based on it the code will fetch the request and response class and perform the operation according to it(not sure about it).
please guide me in doing this,or any other way i can do the above mentioned thing.
Thanks in advance.
Consider using one of the many Java REST libraries. Our client uses the Jersey API to handle requests and responses to our Python based RESTful server.
Jersey uses a class called ClientResponse that stores the generic response data. you can use the getEntity method to return the response as a specific type.
Here is an excerpt of my code, which only deals with strings, but you can see how it could be extended:
ClientResponse response; //a Jersey class
String responseText;
WebResource odbc = resourceCollection.path("ODBC"); //another Jersey class
try {
//we send a POST and get a response stored as generic
response = odbc.type(media)
.accept(MediaType.APPLICATION_XML,MediaType.TEXT_PLAIN)
.post(ClientResponse.class, formdata);
//we pull out the response entity as a string
responseText = response.getEntity(String.class);
} catch (UniformInterfaceException e) {
write("<UniformInterfaceException>\n");
write(" Response type was not expected\n");
write("</UniformInterfaceException>\n");
return;
} catch (ClientHandlerException e) {
write("<Error>\n");
write(" Unable to connect or connection refused\n");
write("</Error>\n");
return;
public class DynamicCasting{
DynamicCasting e1=new DynamicCasting();
private Object obj=new Object();
DynamicCasting.doSomething(obj);
public static DynamicClass doSomething(DynamicClass dynClassObject){
return dynClassObject;
}
}
The obj will be type casted to DynamicClass in this example.
I have a REST WS implemented using Jersey/Jackson. The method which has been implemented is PUT and it is working fine until i get an empty or null body.
After googling a bit, I realized that it is a known issue and there are couple of work arounds available. One of the work around that i found (and implemented) is using ContentRequestFilter to intercept calls, do basic checks and decide what to do.
But in that case, I have to check if the call is for that specific method. I don't like this since what if the method changes in future ?
What i want is to receive as InputStream instead of parsed JacksonObject (Its a custom POJO object created using Jackson Annotations) and parse the inputstream to do that. However, I am unable to find a reference to do that i.e., parsing a jackson object, out of input stream (based on input media type) and return the respective object.
Can someone direct me to some helpful resources or help me here ?
This is an easy way of getting the contents from a request handled by Resource. Just replace Map.class with your annotated POJO:
#POST
public void handle(String requestBody) throws IOException {
ObjectMapper om = new ObjectMapper();
Map result = om.readValue(requestBody, Map.class);
}
With this approach you are free to handle a null value in any way you find suitable.
I want to send a POST request but i want to add XML as string in the post rather adding JAXBObject. The reason is that i am writing some unit test. With JAXBObject, I am limited to provide only valid value in my jaxb generated object via XSD (i.e. valid ENUM Type).
Now i want to test my WS by inputting some random value for that input type so that i can test it.
If i do
ClientResponse clientResponse = service.post(ClientResponse.class, jaxbElement);
It works fine as expected. However I don't want to send the jaxbElement .. I wana send a custom XML say
When you call the following from a test case
ClientResponse response = builder.
accept(MediaType.APPLICATION_JSON).
type(MediaType.APPLICATION_XML).
entity(entityObj).
post(ClientResponse.class);
you can send anything in entity(entityObj)
You can also try SoapUI for REST Tesing