Getting 400 for Spring Resttemplate Post

Getting 400 Bad Request for Spring RestTemplate POST

Just solved the issue by adding following code in dispatcher servlet configuration file of REST Client:

<bean id="jacksonMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter" />
</list>
</property>
</bean>

Full code of dispatcher servlet is:
web-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="webcontroller" />
<mvc:annotation-driven />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>

<bean id="jacksonMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter" />
</list>
</property>
</bean>

</beans>

Also removed some code from REST calling function, below are the changes:
REST CLIENT

try {
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8181/xyz/updateAdmin";
JSONArray json = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("a_username", "testabcd");
obj.put("a_id", 1);
//obj.put("a_password", "N/A");
json.put(obj);
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
headers.add("Content-Type", MediaType.APPLICATION_JSON.toString());
HttpEntity<String> entity = new HttpEntity<String>(obj.toString(), headers);
restTemplate.exchange(url, HttpMethod.POST, entity, String.class);


} catch(Exception ex) {
ex.printStackTrace();
}

Spring boot RestTemplate post giving 400 error

PatentListWrapper is a complex object, not a piece of xml , so the answer is to remove all references to xml ie

  1. Remove @XmlRootElement(name="PatentListWrapper") from PatentListWrapper.
  2. Add jackson-*.jar(s) into the classpath to do the message converting
  3. Change the server side @RequestMapping from :

    @RequestMapping(value = "/xmlList", method = RequestMethod.POST , consumes = { "application/xml" }, produces = { "application/xml" }) 

to

@RequestMapping(value = "/xmlList", method = RequestMethod.POST )

This means that the ARC client now returns JSON (as it's the default return type), even when I send xml, but that's not important as it's just a test tool.

So, when posting objects with RestTemplate in Spring 2, no contentType settings or additional messageConverters are required on the client side , just:

RestTemplate restTemplate = new RestTemplate();
MyObject myObjectReturn = restTemplate.postForObject(url,myObject,MyObject.class);

and on the server side:

@RestController
@RequestMapping(value = "/endPoint", method = RequestMethod.POST)
public MyObject anyMethodName(@RequestBody MyObject myObject) {
//Do stuff to myObject
return myObject;
}

Spring Boot RestTemplate exchange 400 bad request

In your curl request you are using an apikey and encodedapikey. Whereas in your Java code you don't. Next to that you are also passing an encoded URL as the URL to use. This will result in encoding the encoded URL again. So don't do that. Instead use a URL with placeholders and supply values for them.

@RequestMapping(path = "/add")
public @ResponseBody String addFromTo () {

String apikey = "";
String baseurl = "http://demowebshop.webshop8.dk/admin/WEBAPI/v2/orders?start={start}&end={end}&api_key={apikey}";

Map<String, Object> parameters = new HashMap<>();
parameters.put("start", "2018-10-05T20:49:41.745Z");
parameters.put("end", "2018-10-16T06:43:40.926Z");
parameters.put("apikey", apikey);

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setBasicAuth("", apikey);

ResponseEntity<OrderResponse> response = restTemplate.getForEntity(baseurl, OrderResponse.class, parameters);

return "Some text.";
}

The code above uses a proper parameterized URL together with a map containing values for the placeholders. Notice that those aren't encoded, as that will be handled by Spring!. Finally you can simply use the getForEntity method to get the result instead of the exchange method.

A final suggestion, Spring Boot already configures a RestTemplate which you can (re)use. You don't need to create a RestTemplate each time you need one (it is quite a heavy object to create, and after creation it is thread safe so it is enough to have a single instance).

public YourClassCOnstructor(RestTemplateBuilder builder) {
this.restTemplate = builder.basicAuthorization("", apikey).build();
}

Ofcourse you can also put this in an @Bean method and inject the specific RestTemplate into your class.

Getting http 400 Bad Request Error with spring and resttemplate postForObject

I don't know why this is the way it is, but the error was that I had to receive the @RequestBody as TblGps[] Array and not as single object!

Although i've fetched and received the same object before and received the result as single object, ...and then I posted it back to the server, and received it as array of objects ... ist it wired?

Does anybody has an explanation for this behaviour ??

    TblGps gps = (TblGps) restTemplate.getForObject(urlGET,TblGps.class);


// alter the Object Data


gps.setDescr("success");

//POST Object to Service Endpoint
TblGps gpsResult = restTemplate.postForObject(urlPOST, "POST", TblGps.class, gps);

and my Controller code

 @RequestMapping(value="/TblGps/update", method=RequestMethod.POST, consumes = "application/json",produces="application/json")
@ResponseBody public TblGps postSingleObject(@RequestBody TblGps[] gps){

logger.debug("/TblGps/update: " + gps[0].getId());

return Application.DataRepository.save(gps[0]);
}

Spring RestTemplate HTTP Post with parameters cause 400 bad request error

A server will often return an HTTP 400 if the content type is not acceptable for a request. The curl example from instagram uses the -F parameter which specifies multipart post data:

-F, --form CONTENT  Specify HTTP multipart POST data (H)

Therefore, you may want to try explicitly setting the Content-type HTTP header in your RestTemplate request:

HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(mvm, requestHeaders);
ResponseEntity<InstagramResult> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, InstagramResult.class);
InstagramResult result = response.getBody();

As mentioned earlier in the comments, a proxy tool like fiddler can be really useful for debugging. The challenge with this situation is that you are working with SSL, so these tools won't be able to "see" the encrypted communications without special configuration.



Related Topics



Leave a reply



Submit