Related
How can I make a PUT request to a rest service using RestTemplate, so that I get a response also.
The rest service I have to call is:
#RequestMapping(value = /forgotpassword, method = RequestMethod.PUT, produces = "application/json")
public SuccessResponse resetUserPassword(#RequestBody ResetPasswordDTO resetPasswordDTO) throws GenericException {
logger.info("--->reset Password");
return new SuccessResponse(userservice.resetUserPassword(resetPasswordDTO));
}
I need to send one POJO also which has two String properties.
The method put of RestTempalte in (Spring)[https://spring.io/] has no return,so if your want get response from server,please try use POST method.I modify your code like this:
In server side:
#RequestMapping(value = "/forgotpassword", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<SuccessResponse> resetUserPassword(#RequestBody ResetPasswordDTO resetPasswordDTO) throws Exception {
log.info("--->reset Password");
SuccessResponse response = new SuccessResponse();
response.setName(resetPasswordDTO.getUsername());
response.setMessage("success");
return new ResponseEntity<SuccessResponse>(response, HttpStatus.OK);
}
In client side you can use RestTemplate do a request:
ResetPasswordDTO request = new ResetPasswordDTO();
request.setPasswork("Huawei#123");
request.setUsername("c00382802");
ResponseEntity<SuccessResponse> response =template.postForEntity("http://localhost:8080//forgotpassword",request,SuccessResponse.class);
System.out.println(response.getBody().toString());
More info you can get from (Spring)[https://spring.io/]
For PUT use RestTemplate.exchange() method
Example
MyJaxbRequestDataObjectrequest = createMyJaxbRequestDataObject();
Map<String, String> uriArguments= createUriArguments();
String url = restBaseUrl + "/myputservice/{usertId}?servicekey={servicekey}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
HttpEntity<MyJaxbRequestDataObject> entity = new HttpEntity<MyJaxbRequestDataObject>(request, headers);
ResponseEntity<MyJaxbResponseDataObject> responseWrapper = shogunRestTemplate.exchange(url, HttpMethod.PUT, entity, MyJaxbResponseDataObject.class, uriArguments);
MyJaxbResponseDataObjectresponse = responseWrapper.getBody();
I am trying to send a json file over REST Template. When I send it via POST man as MULTIPART_FORM_DATA, it works fine. The name I am supposed to give is specific (lets say aaa). Attached screenshot of POSTMAN. But when I try same in code as specified in another stackoverflow post, I get 415 Unsupported Media Type error as
org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) ~[spring-web-4.1.9.RELEASE.jar:4.1.9.RELEASE]
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:616) ~[spring-web-4.1.9.RELEASE.jar:4.1.9.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:572) ~[spring-web-4.1.9.RELEASE.jar:4.1.9.RELEASE]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:532) ~[spring-web-4.1.9.RELEASE.jar:4.1.9.RELEASE]
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:332) ~[spring-web-4.1.9.RELEASE.jar:4.1.9.RELEASE]
at
Please do not mark it as duplicate as the specified answer did not work for me. Not sharing code as my code is exactly same as this except
requestParamerterMap.add("attachment", resource);
where as my code is
requestParamerterMap.add("aaa", resource);
After debugging it from the server side, looks like request is reaching out to server. I was able to see below error in the server side:
[{error=Unsupported Media Type, exception=org.springframework.web.HttpMediaTypeNotSupportedException, message=Content type 'application/octet-stream' not supported, status=415, timestamp=1532557180124}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#74d4827a]
So, from the server side logs, I am not sure where the content type is getting added as application/octet-stream as I have set the content type as
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
Below is the code from server controller. Server side code uses Spring boot.
#RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE,consumes = {"multipart/form-data"})
#ResponseBody
public MyResponse uploadPhoto(#RequestPart(value = "aaa", required = false) Optional<MyRequest> myRequest,
#RequestPart(value = "file", required = false) Optional<MultipartFile> file,
HttpServletRequest request) {
//some logic
return myResponse;
}
The server code has an interceptor where I can see my request has content type as multipart/form-data. It does not reach to RestController
When I debugged the server side code in 2 cases:
POSTMAN request
client code request
One thing I figured out that file iteam has content type as application/json when I post from POSTMAN and the content type was application/octet-stream when the request goes from client side code.
In my client side code, I am creating JSONObject as
JSONObject json = new JSONObject();
json.append("myKey", "myValue");
and convert it to byte array as
json.toString().getBytes("UTF-8")
then I have followed this . The difference in my code is, I am sending my JSONObject as byte stream as I can not create file (performance issues).
And I cant not send JSONObject as string as server is expecting multipart-form-data for both file and aaa
I have created the restTemplate as
public RestTemplate myRestTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setReadTimeout(HTTP_CLIENT_TIMEOUT);
requestFactory.setConnectTimeout(HTTP_CLIENT_TIMEOUT);
RestTemplate restTemplate = new RestTemplate(requestFactory);
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new FormHttpMessageConverter());
messageConverters.add(new StringHttpMessageConverter());
restTemplate.setMessageConverters(messageConverters);
return restTemplate;
Here is the client side code which calls the service:
public Optional<JSONObject> callService(byte[] multipartFile) {
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
InputStream stream = new ByteArrayInputStream(multipartFile);
MultipartByteArrayResource resource = new MultipartByteArrayResource(multipartFile,fileName);
body.add("aaa", resource);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
try {
response = restTemplate.postForObject(url, requestEntity , String.class);
} catch (Exception exception) {
LOG.error("Error", exception);
return Optional.empty();
}
}
public class MultipartInputStreamFileResource extends InputStreamResource {
private final String filename;
MultipartInputStreamFileResource(InputStream inputStream, String filename) {
super(inputStream);
this.filename = filename;
}
#Override
public String getFilename() {
return this.filename;
}
#Override
public long contentLength() throws IOException {
return -1; // we do not want to generally read the whole stream into memory ...
}
}
And same code works when I send file (note file and aaa are two different things though both are multipart/form-data in server side. file is just a file of any time (image/text/pdf) but aaa is json data file)
After debugging little bit more, what I observed is server side controller is expecting the file content to be json as Jackson try to deserialize that json to MyRequest object. When I send post from POSTMAN, it has the json content so working as expected but from the client side code, the content is byteArray, and its not getting deserialize to MyRequest object. Not sure how to fix this
Finally I solved this issue. As mentioned in question, having different content type of multipart file while sending request from POSTMAN vs code is where I began with. I will explain in details if anyone has any questions.
public Optional<JSONObject> save(byte[] multipartFile, String fileName) {
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
Resource content = new MultipartByteArrayResource(multipartFile , fileName);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Resource> requestEntityBody = new HttpEntity<Resource>(content, headers);
body.add("aaa", requestEntityBody);
String result = "";
JSONParser parser = new JSONParser();
JSONObject json = null;
HttpHeaders requestHeaders = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, requestHeaders);
ResponseEntity<String> response = null;
try {
RestTemplate restTemplate = customizeRestTemplate(); //I have defined this in different config file in my actual code
response = restTemplate.exchange(url , HttpMethod.POST , requestEntity , String.class);
result = (response != null && response.getBody() != null) ? response.getBody().toString() : result;
json = (JSONObject) parser.parse(result);
LOG.info( "Response:", response );
} catch (Exception exception) {
LOG.error("Error , exception);
return Optional.empty();
}
return Optional.ofNullable(json);
}
public class MultipartByteArrayResource extends ByteArrayResource{
private String fileName;
public MultipartByteArrayResource(byte[] byteArray , String filename) {
super(byteArray);
this.fileName = filename;
}
public String getFilename() {
return fileName;
}
public void setFilename(String fileName) {
this.fileName= fileName;
}
}
public RestTemplate customizeRestTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setReadTimeout(10000);
requestFactory.setConnectTimeout(10000);
RestTemplate restTemplate = new RestTemplate(requestFactory);
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new FormHttpMessageConverter());
messageConverters.add(new StringHttpMessageConverter());
restTemplate.setMessageConverters(messageConverters);
return restTemplate;
}
}
The server-side exception is produced by org.springframework.http.converter.json.MappingJackson2HttpMessageConverter. Jackson is a JSON library and MessageConverter are used by Spring to format requests and responses.
Can it be that the client sends an "Accept: application/octet-stream" while the server has a #Produces(APPLICATION_JSON) annotation? That would mean that the server processes the request and only has problems sending the response. You could add some log.info() statements in the server to verify this.
Please look at this simple code:
final String url = String.format("%s/api/shop", Global.webserviceUrl);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.set("X-TP-DeviceID", Global.deviceID);
HttpEntity entity = new HttpEntity(headers);
HttpEntity<Shop[]> response = restTemplate.exchange(url, HttpMethod.GET, entity, Shop[].class);
shops = response.getBody();
As you can see, above code is intended to GET list of shops from server (in json format) and map response to array of Shop objects.
Now I need to PUT new shop, for example as /api/shop/1. Request entity should have exactly the same format as returned one.
Should I add /1 to my url, create new Shop class object, with all fields filled with my values I want to put and then use exchange with HttpMethod.PUT?
Please, clarify it for me, I'm beginner with Spring. Code example would be appreciated.
[edit]
I'm double confused, because I just noticed also method RestTemplate.put(). So, which one should I use? Exchange or put()?
You could try something like :
final String url = String.format("%s/api/shop/{id}", Global.webserviceUrl);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.set("X-TP-DeviceID", Global.deviceID);
Shop shop= new Shop();
Map<String, String> param = new HashMap<String, String>();
param.put("id","10")
HttpEntity<Shop> requestEntity = new HttpEntity<Shop>(shop, headers);
HttpEntity<Shop[]> response = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, Shop[].class, param);
shops = response.getBody();
the put returns void whereas exchange would get you a response, the best place to check would be documentation https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html
I have a POST API written in Restlet framework which accepts the data in org.restlet.representation.Representation form, I want to hit the service with some variables and there values from Spring project. How to do that?
Right now I am using the HTTPHeaders to send the data but the API is not accepting the values, all the fields the API is showing as NULL. The code is as follows:
final String uri = "http://localhost:8080/MyServices/adduser";
String userid = "05580a6caa7244a6986ca834403f1a93";
String usertype = "buyer";
String username = "shivam42";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.add("userid", userid);
headers.add("usertype", usertype);
headers.add("username", username);
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST, entity, String.class);
System.out.println(result);
And the service is like this:
#Post
public String newUser(Representation entity) {
Form form = new Form(entity);
String userid = form.getValues("userid");
String usertype = form.getValues("usertype");
String username = form.getValues("username");
System.out.println(userid);
System.out.println(usertype);
System.out.println(username);
return userid;
}
This is the code generated from curl Maybe someone can help me with this:
curl -X POST -H "Cache-Control: no-cache" -H "Postman-Token: 33e6a1c5-c1c9-694f-3d7f-26cbcea61870" -H "Content-Type: application/x-www-form-urlencoded" -d 'userid=05580a6caa7244a6986ca834403f1a93&usertype=buyer&username=shivam42' "http://localhost:8080/MyServices/adduser"
When I am calling the API from POSTMAN it is giving me the correct userid, now how to call it from Spring project? Am I doing something wrong?
#Shivam Thanks for updating the question. With the curl command in place I now see that the data you basically wanted to send is inside the request's body. Therefore the first approach with HttpHeaders won't work. Here's an example of how it could look like for your first approach using the exchange method of Springs RestTemplate:
#Test
public void test() {
RestTemplate restTemplate = new RestTemplate();
final String uri = "http://localhost:8080/adduser";
String userid = "05580a6caa7244a6986ca834403f1a93";
String usertype = "buyer";
String username = "shivam42";
// create request body
JSONObject request = new JSONObject();
request.put("userid", userid);
request.put("usertype", usertype);
request.put("username", username);
// set headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(request.toString(), headers);
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST, entity, String.class);
System.out.println(result.getBody());
}
This should also work as expected and return the userid. See also POST request via RestTemplate in JSON for further information.
From the Spring forum I found the solution to this.
Now my code is:
final String uri = "http://localhost:8080/MyServices/adduser";
String userid = "05580a6caa7244a6986ca834403f1a93";
String usertype = "buyer";
String username = "shivam42";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("userid", userid);
params.add("usertype", usertype);
params.add("username", username);
RestTemplate restTemplate = new RestTemplate();
HttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
HttpMessageConverter stringHttpMessageConverternew = new StringHttpMessageConverter();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(stringHttpMessageConverternew);
messageConverters.add(formHttpMessageConverter);
restTemplate.setMessageConverters(messageConverters);
System.out.println(restTemplate.postForObject(uri, params, String.class));
In my case I am also getting the expected result If I exclude the following code:
HttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
HttpMessageConverter stringHttpMessageConverternew = new StringHttpMessageConverter();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(stringHttpMessageConverternew);
messageConverters.add(formHttpMessageConverter);
restTemplate.setMessageConverters(messageConverters);
I didn't find any example how to solve my problem, so I want to ask you for help. I can't simply send POST request using RestTemplate object in JSON
Every time I get:
org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type
I use RestTemplate in this way:
...
restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
list.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(list);
...
Payment payment= new Payment("Aa4bhs");
Payment res = restTemplate.postForObject("http://localhost:8080/aurest/rest/payment", payment, Payment.class);
What is my fault?
This technique worked for me:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
ResponseEntity<String> response = restTemplate.put(url, entity);
I ran across this problem when attempting to debug a REST endpoint. Here is a basic example using Spring's RestTemplate class to make a POST request that I used. It took me quite a bit of a long time to piece together code from different places to get a working version.
RestTemplate restTemplate = new RestTemplate();
String url = "endpoint url";
String requestJson = "{\"queriedQuestion\":\"Is there pain in your hand?\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String answer = restTemplate.postForObject(url, entity, String.class);
System.out.println(answer);
The particular JSON parser my rest endpoint was using needed double quotes around field names so that's why I've escaped the double quotes in my requestJson String.
I've been using rest template with JSONObjects as follow:
// create request body
JSONObject request = new JSONObject();
request.put("username", name);
request.put("password", password);
// set headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(request.toString(), headers);
// send request and parse result
ResponseEntity<String> loginResponse = restTemplate
.exchange(urlString, HttpMethod.POST, entity, String.class);
if (loginResponse.getStatusCode() == HttpStatus.OK) {
JSONObject userJson = new JSONObject(loginResponse.getBody());
} else if (loginResponse.getStatusCode() == HttpStatus.UNAUTHORIZED) {
// nono... bad credentials
}
As specified here I guess you need to add a messageConverter for MappingJacksonHttpMessageConverter
I'm doing in this way and it works .
HttpHeaders headers = createHttpHeaders(map);
public HttpHeaders createHttpHeaders(Map<String, String> map)
{
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
for (Entry<String, String> entry : map.entrySet()) {
headers.add(entry.getKey(),entry.getValue());
}
return headers;
}
// Pass headers here
String requestJson = "{ // Construct your JSON here }";
logger.info("Request JSON ="+requestJson);
HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
logger.info("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
logger.info("Response ="+response.getBody());
Hope this helps
If you are using Spring 3.0, an easy way to avoid the org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type exception, is to include the jackson jar files in your classpath, and use mvc:annotation-driven config element. As specified here.
I was pulling my hair out trying to figure out why the mvc-ajax app worked without any special config for the MappingJacksonHttpMessageConverter. If you read the article I linked above closely:
Underneath the covers, Spring MVC
delegates to a HttpMessageConverter to
perform the serialization. In this
case, Spring MVC invokes a
MappingJacksonHttpMessageConverter
built on the Jackson JSON processor.
This implementation is enabled
automatically when you use the
mvc:annotation-driven configuration
element with Jackson present in your
classpath.
The "415 Unsupported Media Type" error is telling you that the server will not accept your POST request. Your request is absolutely fine, it's the server that's mis-configured.
MappingJacksonHttpMessageConverter will automatically set the request content-type header to application/json, and my guess is that your server is rejecting that. You haven't told us anything about your server setup, though, so I can't really advise you on that.
Why work harder than you have to? postForEntity accepts a simple Map object as input. The following works fine for me while writing tests for a given REST endpoint in Spring. I believe it's the simplest possible way of making a JSON POST request in Spring:
#Test
public void shouldLoginSuccessfully() {
// 'restTemplate' below has been #Autowired prior to this
Map map = new HashMap<String, String>();
map.put("username", "bob123");
map.put("password", "myP#ssw0rd");
ResponseEntity<Void> resp = restTemplate.postForEntity(
"http://localhost:8000/login",
map,
Void.class);
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
}
I was getting this problem and I'm using Spring's RestTemplate on the client and Spring Web on the server. Both APIs have very poor error reporting, making them extremely difficult to develop with.
After many hours of trying all sorts of experiments I figured out that the issue was being caused by passing in a null reference for the POST body instead of the expected List. I presume that RestTemplate cannot determine the content-type from a null object, but doesn't complain about it. After adding the correct headers, I started getting a different server-side exception in Spring before entering my service method.
The fix was to pass in an empty List from the client instead of null. No headers are required since the default content-type is used for non-null objects.
This code is working for me;
RestTemplate restTemplate = new RestTemplate();
Payment payment = new Payment("Aa4bhs");
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("payment", payment);
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(map, headerObject);
Payment res = restTemplate.postForObject(url, httpEntity, Payment.class);
If you dont want to process response
private RestTemplate restTemplate = new RestTemplate();
restTemplate.postForObject(serviceURL, request, Void.class);
If you need response to process
String result = restTemplate.postForObject(url, entity, String.class);
I tried as following in spring boot:
ParameterizedTypeReference<Map<String, Object>> typeRef = new ParameterizedTypeReference<Map<String, Object>>() {};
public Map<String, Object> processResponse(String urlendpoint)
{
try{
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//reqobj
JSONObject request = new JSONObject();
request.put("username", name);
//Or Hashmap
Map<String, Object> reqbody = new HashMap<>();
reqbody.put("username",username);
Gson gson = new Gson();//mvn plugin to convert map to String
HttpEntity<String> entity = new HttpEntity<>( gson.toJson(reqbody), headers);
ResponseEntity<Map<String, Object>> response = resttemplate.exchange(urlendpoint, HttpMethod.POST, entity, typeRef);//example of post req with json as request payload
if(Integer.parseInt(response.getStatusCode().toString()) == HttpURLConnection.HTTP_OK)
{
Map<String, Object> responsedetails = response.getBody();
System.out.println(responsedetails);//whole json response as map object
return responsedetails;
}
} catch (Exception e) {
// TODO: handle exception
System.err.println(e);
}
return null;
}
For me error occurred with this setup:
AndroidAnnotations
Spring Android RestTemplate Module
and ...
GsonHttpMessageConverter
Android annotations has some problems with this converted to generate POST request without parameter. Simply parameter new Object() solved it for me.
If you don't want to map the JSON by yourself, you can do it as follows:
RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter()));
ResponseEntity<String> result = restTemplate.postForEntity(uri, yourObject, String.class);
You can make request as a JSON object
JSONObject request = new JSONObject();
request.put("name","abc");
ResponseEntity<JSONObject> response =restTemplate.postForEntity(append_url,request,JSONObject.class); `enter code here`