Sending text REST message in Java w/ Spring - java

I have written a REST Request mapper:
#RequestMapping(value = "/resttest", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> receiveBody(#RequestBody String bodymsg,HttpServletRequest request) {
String header_value = request.getHeader("h_key");
return new ResponseEntity<String>(HttpStatus.OK);
}
I would like to send a POST method to this like that:
public static void sendpost() {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("h_key","this is the value you need");
HttpEntity<String> entity = new HttpEntity<String>("text body", headers);
ResponseEntity<JSONObject> response = restTemplate
.exchange("http://localhost:9800/resttest", HttpMethod.POST, entity,JSONObject.class);
}
But I get this error:
Unsupported Media Type
What is the problem with my sending method?

You set server side to accept plan text only, but your request sets content_type to "application/json"... means you are telling server side that you are sending JSON format, so that server side says "I don't support this media type" ( http error code 415 )
For what you said
I tried with REST GUI client sending data to controller and worked fine.
if you specify "content-type" in the REST GUI as "text/plain", probably you will get an same error code.
For
If I change the Controller consumes part to: ALL_VALUE it works fine.
, that's because now you are telling to server side code to take all the media type (Content-Type), so whatever value you set up in client side request, it doesn't matter anymore.

Related

PostForEntity: 415 Unsupported Media Type

In our project, we call an external API with postForEntity and receive the following: error:org.springframework.web.server.ResponseStatusException: 415 UNSUPPORTED_MEDIA_TYPE "Could not determine reason or message. Plain body: ""
final ActionDto actionDto = new ActionDto ().setRequestId(requestId);
final ResponseEntity<ActionResponseDto> response = restTemplate.postForEntity(url, actionDto, ActionResponseDto.class);
I managed to fix this error by using exchange instead of postForEntity and adding a media type:
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
val entity = new HttpEntity(actionDto , headers);
final ResponseEntity<ActionResponseDto> response =
restTemplate.exchange(
url,
HttpMethod.POST,
entity,
ActionResponseDto.class);
My question is the following, could you give me some hints why before with postForEntity it worked and now suddenly it doesn't?
I also checked the external API and the method looks like bellow, and nothing has changed:
#PostMapping("/action/start")
#ResponseStatus(HttpStatus.OK)
#Operation(summary = "Start the action")
public ResponseEntity<ActionResponseDto> startAction(#RequestBody final ActionDto requestDto) {
.....
}
Could it be due to some dependencies? This error is very strange...
Thank you! :)

RESTful Api - Spring MediaType vs Restlet MediaType

I have an REST client:
import org.restlet.representation.ObjectRepresentation;
import org.restlet.data.MediaType;
ObjectRepresentation<ApprovalResponse> objectRepresentation = (ObjectRepresentation<ApprovalResponse>) cr.post(approvalRequest, MediaType.APPLICATION_JAVA_OBJECT);
And a Spring Boot Service RESTful api:
import org.springframework.http.MediaType;
#PostMapping(value = "/rest/approvals-submit")
public #ResponseBody ApprovalResponse submit(#RequestHeader(name="Authorization") String token, #RequestBody ApprovalRequest approvalRequest) {
System.out.println("jwt token: "+token);
System.out.println(approvalRequest.getMessageToEvaluator());
ApprovalResponse approvalResponse = new ApprovalResponse();
approvalResponse.setApprovalId("Test approvalResponse from micro service");
return approvalResponse;
}
The client calls the API successfully. i.e. the System.out.println(approvalRequest.getMessageToEvaluator()); is printed out successfully.
Problem
My issue is that the response object is not getting back to the REST client.
Error Messages
Rest client
org.restlet.resource.ResourceException: Not Acceptable (406) - The
resource identified by the request is only capable of generating
response entities which have content characteristics not acceptable
according to the accept headers sent in the request
Server/Api
Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException:
Could not find acceptable representation]
Question
So I think these errors are because the MediaTypes are not defined correctly. Do you know what they should be defined as?
Update after having a direct chat
We added on the rest endpoint, on the postMapping annotation the following:
#PostMapping(value = "/rest/approvals-submit")
public #ResponseBody ApprovalResponse submit(#RequestHeader(name="Authorization") String token, #RequestBody ApprovalRequest approvalRequest, produces={MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE},consumes = MediaType.APPLICATION_JSON_VALUE) {
System.out.println("jwt token: "+token);
System.out.println(approvalRequest.getMessageToEvaluator());
ApprovalResponse approvalResponse = new ApprovalResponse();
approvalResponse.setApprovalId("Test approvalResponse from micro service");
return approvalResponse;
}
This added on the #PostMapping annotation produces={MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE},consumes = MediaType.APPLICATION_JSON_VALUE.
On client side, we change the response type to Representation, and we were able to get the json response:
ClientResource cr = new ClientResource(endpointUrl);
ChallengeResponse challengeResponse = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
challengeResponse.setRawValue(token);
cr.setChallengeResponse(challengeResponse);
Request req = cr.getRequest();
Representation representation = cr.post(approvalRequest);
System.out.println(representation.getText());
Finally, using Jackson Object Mapper the response could be mapped into the Approval response object:
// now convert the response to java
ObjectMapper objectMapper = new ObjectMapper();
ApprovalResponse approvalResponse = objectMapper.readValue(json, ApprovalResponse.class);
System.out.println(approvalResponse);
System.out.println(approvalResponse.getApprovalId());
It was a content negotiation issue. The content negotiation it's done via the Content-Type header, for better understanding of it, you could read this blog entry

How to extract HTTP status code from the RestTemplate call to a URL?

I am using RestTemplate to make an HTTP call to our service which returns a simple JSON response. I don't need to parse that JSON at all. I just need to return whatever I am getting back from that service.
So I am mapping that to String.class and returning the actual JSON response as a string.
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url, String.class);
return response;
Now the question is -
I am trying to extract HTTP Status codes after hitting the URL. How can I extract HTTP Status code from the above code? Do I need to make any change into that in the way I doing it currently?
Update:-
This is what I have tried and I am able to get the response back and status code as well. But do I always need to set HttpHeaders and Entity object like below I am doing it?
RestTemplate restTemplate = new RestTemplate();
//and do I need this JSON media type for my use case?
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//set my entity
HttpEntity<Object> entity = new HttpEntity<Object>(headers);
ResponseEntity<String> out = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
System.out.println(out.getBody());
System.out.println(out.getStatusCode());
Couple of question - Do I need to have MediaType.APPLICATION_JSON as I am just making a call to url which returns a response back, it can return either JSON or XML or simple string.
Use the RestTemplate#exchange(..) methods that return a ResponseEntity. This gives you access to the status line and headers (and the body obviously).
getStatusCode()
getHeaders()
If you don´t want to leave the nice abstraction around RestTemplate.get/postForObject... methods behind like me and dislike to fiddle around with the boilerplate stuff needed when using RestTemplate.exchange... (Request- and ResponseEntity, HttpHeaders, etc), there´s another option to gain access to the HttpStatus codes.
Just surround the usual RestTemplate.get/postForObject... with a try/catch for org.springframework.web.client.HttpClientErrorException and org.springframework.web.client.HttpServerErrorException, like in this example:
try {
return restTemplate.postForObject("http://your.url.here", "YourRequestObjectForPostBodyHere", YourResponse.class);
} catch (HttpClientErrorException | HttpServerErrorException httpClientOrServerExc) {
if(HttpStatus.NOT_FOUND.equals(httpClientOrServerExc.getStatusCode())) {
// your handling of "NOT FOUND" here
// e.g. throw new RuntimeException("Your Error Message here", httpClientOrServerExc);
}
else {
// your handling of other errors here
}
The org.springframework.web.client.HttpServerErrorException is added here for the errors with a 50x.
Now you´re able to simple react to all the StatusCodes you want - except the appropriate one, that matches your HTTP method - like GET and 200, which won´t be handled as exception, as it is the matching one. But this should be straight forward, if you´re implementing/consuming RESTful services :)
If you want all the HTTPStatus from a RestTemplate including 4XX and 5XX, you will have to provide an ResponseErrorHandler to the restTemplate, since the default handler will throw an exception in case of 4XX or 5XX
We could do something like that :
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
#Override
public boolean hasError(HttpStatus statusCode) {
return false;
}
});
ResponseEntity<YourResponse> responseEntity =
restTemplate.getForEntity("http://your.url.here", YourResponse.class);
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.XXXX);
private RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange(url,HttpMethod.GET, requestEntity,String.class);
response contains 'body', 'headers' and 'statusCode'
to get statusCode : response.getStatusCode();
exchange(...) works but if you want less code, you can use
org.springframework.boot.test.web.client.TestRestTemplate.getForEntity(...)
which returns an Entity containing StatusCode. Change your example code to this:
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
HttpStatus statusCode = response.getStatusCode();
To test it you can use this snippet from my unit test:
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
assertResponseHeaderIsCorrect(response, HttpStatus.OK);
/**
* Test the basics of the response, non-null, status expected, etc...
*/
private void assertResponseHeaderIsCorrect(ResponseEntity<String> response, HttpStatus expectedStatus) {
assertThat(response).isNotNull();
assertThat(response.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON_UTF8);
assertThat(response.getStatusCode()).isEqualTo(expectedStatus);
}
There can be some slightly trickier use cases someone might fall in (as I did). Consider the following:
Supporting a Page object in order to use it with RestTemplate and ParameterizedTypeReference:
RestPageResponse:
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
public class RestResponsePage<T> extends PageImpl<T>{
private static final long serialVersionUID = 3248189030448292002L;
public RestResponsePage(List<T> content, Pageable pageable, long total) {
super(content, pageable, total);
}
public RestResponsePage(List<T> content) {
super(content);
}
public RestResponsePage() {
super(new ArrayList<T>());
}
}
Using ParameterizedTypeReference will yield the following:
ParameterizedTypeReference<RestResponsePage<MyObject>> responseType =
new ParameterizedTypeReference<RestResponsePage<MyObject>>() {};
HttpEntity<RestResponsePage<MyObject>> response = restTemplate.exchange(oauthUrl, HttpMethod.GET, entity, responseType);
Calling #exchange:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<?> entity = new HttpEntity<>(headers);
response = restTemplate.exchange("localhost:8080/example", HttpMethod.GET, entity, responseType);
Now here is the "tricky" part.
Trying to call exchange's getStatusCode will be impossible because the compiler, unfortunately, will be unaware of the "intended" type of response.
That is because generics are implemented via type erasure which removes all information regarding generic types during compilation (read more - source)
((ResponseEntity<RestResponsePage<MyObject>>) response).getStatusCode()
In this case, you have to explicitly cast the variable to the desired Class to get the statusCode (and/or other attributes)!
Putting this much of code is enough for me
HttpStatus statusCode = ((ResponseEntity<Object>) responseOfEsoft).getStatusCode();
You can use this solution
RestTemplate restTemplate = new RestTemplate();
final String baseUrl = "http://www.myexampleurl.com";
URI uri = new URI(baseUrl);
ResponseEntity<String> result = restTemplate.getForEntity(uri, String.class);
//get status code
int statuCode = result.getStatusCodeValue();
Was able to solve this through:
HttpEntity<Object> entity = restTemplate.getForEntity(uri, Object.class);
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
System.out.println(result.getStatusCode());

Why RestTemplate GET response is in JSON when should be in XML?

I struggled with an extrange spring behavior using RestTemplate (org.springframework.web.client.RestTemplate) without success.
I use in my hole application below code and always receive an XML response, which I parse and evaluate its result.
String apiResponse = getRestTemplate().postForObject(url, body, String.class);
But can't figure out why a server response is in JSON format after executing:
String apiResponse = getRestTemplate().getForObject(url, String.class);
I've debugged at low level RestTemplate and the content type is XML, but have no idea why the result is in JSON.
When I access from a browser the response is also in XML, but in apiResponse I got JSON.
I tried many options after reading Spring documentation
http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/web/client/RestTemplate.html
Also tried to modify explicitly the headers but still can't figure it out.
I debugged RestTemplate class and noticed that this method is always setting application/json:
public void doWithRequest(ClientHttpRequest request) throws IOException {
if (responseType != null) {
List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
for (HttpMessageConverter<?> messageConverter : getMessageConverters()) {
if (messageConverter.canRead(responseType, null)) {
List<MediaType> supportedMediaTypes = messageConverter.getSupportedMediaTypes();
for (MediaType supportedMediaType : supportedMediaTypes) {
if (supportedMediaType.getCharSet() != null) {
supportedMediaType =
new MediaType(supportedMediaType.getType(), supportedMediaType.getSubtype());
}
allSupportedMediaTypes.add(supportedMediaType);
}
}
}
if (!allSupportedMediaTypes.isEmpty()) {
MediaType.sortBySpecificity(allSupportedMediaTypes);
if (logger.isDebugEnabled()) {
logger.debug("Setting request Accept header to " + allSupportedMediaTypes);
}
request.getHeaders().setAccept(allSupportedMediaTypes);
}
}
}
Could you give an idea?
I could solve my issue with RC.'s help. I'll post the answer to help other people.
The problem was that Accept header is automatically set to APPLICATION/JSON so I had to change the way to invoke the service in order to provide the Accept header I want.
I changed this:
String response = getRestTemplate().getForObject(url, String.class);
To this in order to make the application work:
// Set XML content type explicitly to force response in XML (If not spring gets response in JSON)
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = getRestTemplate().exchange(url, HttpMethod.GET, entity, String.class);
String responseBody = response.getBody();

Optional Request Header in Spring Rest Service

I'm using Spring Restful web service & having request body with request header as shown below:
#RequestMapping(value = "/mykey", method = RequestMethod.POST, consumes="applicaton/json")
public ResponseEntity<String> getData(#RequestBody String body, #RequestHeader("Auth") String authorization) {
try {
....
} catch (Exception e) {
....
}
}
I want to pass one more optional request header called "X-MyHeader". How do I specify this optional request header in Spring rest service?
Also, how do I pass this same value in response header??
Thanks!
UPDATE: I just found that I can set required=false in request header, so one issue is resolved. Now, the only issue remaining is how do I set the header in the response??
Use required=false in your #RequestHeader:
#PostMapping("/mykey")
public ResponseEntity<String> getData(
#RequestBody String body,
#RequestHeader(value = "Auth", required = false) String authorization) {}
This question is answered here:
In Spring MVC, how can I set the mime type header when using #ResponseBody
Here is a code sample from: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-httpentity
#RequestMapping("/something")
public ResponseEntity<String> handle(HttpEntity<byte[]> requestEntity) throws UnsupportedEncodingException {
String requestHeader = requestEntity.getHeaders().getFirst("MyRequestHeader");
byte[] requestBody = requestEntity.getBody();
// do something with request header and body
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue");
return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}

Categories

Resources