Post data using Spring RestTemplate - spring

I am trying to post data using Spring RestTemplate as below:
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
parameters.add("name1", "value1");
parameters.add("name2", "value2");
HttpMessageConverter<String> stringConverter = new StringHttpMessageConverter();
FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
List<HttpMessageConverter<?>> msgConverters = new ArrayList<HttpMessageConverter<?>>();
msgConverters.add(formConverter);
msgConverters.add(stringConverter);
restTemplate.setMessageConverters(msgConverters);
String xml = restTemplate.postForObject(myurl, parameters, String.class);
On the server part, I am using a simple servlet to handle request as follow:
String name1 = request.getParameter("name1");
The server returns the xml as String.
When I used HashMap instead of MultiValueMap without Converter, the parameters are null on the server side. But after using the above code, I am getting error
Cannot extract response: no Content-Type found
Can you plz provide me a simple example to achieve what I want.

Here is what I used to format data for the Spring POST:
//FormHttpMessageConverter
is used to construct form parameters to POST on the URI
HttpMessageConverter<?> formHttpMessageConverter = new FormHttpMessageConverter();
HttpMessageConverter<?> stringHttpMessageConverter = new StringHttpMessageConverter();
List<HttpMessageConverter> msgConverters = new ArrayList<HttpMessageConverter>();
msgConverters.add(formHttpMessageConverter);
msgConverters.add(stringHttpMessageConverter);
// Prepare acceptable media type
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.ALL);
// Prepare header
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
HttpEntity<MultiValueMap<String,String>> httpEntity = new HttpEntity<MultiValueMap<String,String>>(map,headers);
ResponseEntity<String> resp = restTemplate.exchange("https://risk.XXXX.XXXXXX.net",HttpMethod.POST,httpEntity,String.class);

Related

RestTemplate - 415 UNSUPPORTED_MEDIA_TYPE Error

I want to call a REST service from my application. I'm not passing any request to this call. But I can't figure out from where it comes from?
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("username", bonitaUsername);
map.add("password", bonitaPassword);
map.add("redirect", "false");
HttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
HttpMessageConverter stringHttpMessageConverternew = new StringHttpMessageConverter();
List<HttpMessageConverter<?>> converters = new ArrayList<>();
converters.add(formHttpMessageConverter);
converters.add(stringHttpMessageConverternew);
restTemplate.setMessageConverters(converters);
HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(map, headers);
ResponseEntity<?> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
List<String> cookies = response.getHeaders().get("Set-Cookie");
String cookieString = "";
for (String cookie : cookies) {
System.out.println();
cookieString += cookie.split(";")[0] + "; ";
}
return cookieString;
This happens due to the mismatch of content types which passing to REST template. Please make sure to send the correct content type. Some times we are receiving JSON request but we need to send as another format.

Okhttp create MultipartBody with spring MultipartFile and json object

I have a controller like so that accepts a MultipartFile and json object:
#PostMapping(value = "/v1/submit")
public ResponseEntity submit(
#RequestParam(value="myFile", required = true) MultipartFile myFile
, #Valid #RequestPart(value="fileMeta", required=true) FileMeta fileMeta
){
I need to forward this to a new url using an okhttpclient post with a Multipartbody containing both myFile and fileMeta objects:
OkHttpClient client = new OkHttpClient();
MultipartBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("myFile", myFile.getName(), okhttp3.RequestBody.create(file, MediaType.parse("pdf"))
.addFormDataPart("fileMeta", fileMeta)
.build();
I am getting following error:
Cannot resolve method 'create(org.springframework.web.multipart.MultipartFile, okhttp3.MediaType)'
The method definition of OkHttp's RequestBody create is the following: create(MediaType contentType, byte[] content). It expects the first the MediaType and second the payload (either as byte[], File or other formats).
So you first have to switch the order of the method arguments and second convert the MultipartFile from Spring to a proper format that the create() method accepts, e.g. byte[] or File:
OkHttpClient client = new OkHttpClient();
MultipartBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("myFile", myFile.getName(), RequestBody.create(MediaType.parse("pdf"), file)
.addFormDataPart("fileMeta", fileMeta)
.build();
There are already multiple solutions available on StackOverflow to convert MultipartFile to File: How to convert a multipart file to File?
UPDATE: Example for using RestTemplate
#RestController
public class FileSendingController {
#PostMapping("/files")
public void streamFile(#RequestParam("file") MultipartFile file) {
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", file);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
RestTemplate restTemplate = new RestTemplate();
restTemplate.postForEntity("http://upload.to", requestEntity, String.class);
}
}

How to send body content as raw JSON and not form-data in Spring Boot RestTemplate

I have a spring boot application and trying to invoke a rest service of another company by using RestTemplate.
The remote Rest Service required multiple header and body content as Raw JSON.
Here is the sample required body request :
{
"amount": "10000",
"destinationNumber": "365412"
}
But my request body generate like this :
{
amount= [10000],
destinationNumber= [365412]
}
I've done like this :
String BASE_URI = "http://server.com/sericeX";
RestTemplate template = new RestTemplate();
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Authorization","Some token");
headers.add("Content-Type", "application/json");
MultiValueMap<String, String> bodyParam = new LinkedMultiValueMap<>();
bodyParam.add("amount", request.getAmount());
bodyParam.add("destinationNumber",request.getDestinationNumber());
HttpEntity entity = new HttpEntity(bodyParam,headers);
ResponseEntity<TransferEntity> responseEntity = template.exchange(BASE_URI, HttpMethod.POST, entity,TransferEntity.class);
TransferEntity transferEntity = responseEntity.getBody();
Could you please tell me how can i generate body request as JSON ?
Thanks to #Alex Salauyou based on his comment using HashMap instead of MultiValueMap solved the problem. Here is the changes need to be done:
HashMap<String, String> bodyParam = new HashMap<>();
bodyParam.put("amount", request.getAmount());
bodyParam.put("destinationNumber",request.getDestinationNumber());

Spring Rest Template to send JsonArray

I am using spring rest template to send json array as request. Source code to send request is as follow:
JSONArray jsonArray = new JSONArray();
for (Iterator iterator = itemlist.iterator(); iterator.hasNext();) {
Item item = (Item)iterator.next();
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", item.getItemConfId());
formDetailsJson.put("name", item.getItems().getItemName());
formDetailsJson.put("price", item.getPrice());
formDetailsJson.put("Cost",item.getCost());
jsonArray.put(formDetailsJson);
}
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
// Prepare header
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
// Pass the new person and header
HttpEntity<JSONArray> entity = new HttpEntity<JSONArray>(jsonArray, headers);
System.out.println("Json Object : "+entity);
// Send the request as POST
try {
ResponseEntity<String> result = restTemplate.exchange("my url", HttpMethod.POST, entity, String.class);
} catch (Exception e) {
logger.error(e);
return "Connection not avilable please try again";
}
And to accept request:
#RequestMapping(value = "/testStock", method = RequestMethod.POST,headers="Accept=application/xml, application/json")
public #ResponseBody int testStock(#RequestBody List<ItemList> jsonArray) {
logger.debug("Received request to connect ms access : "+jsonArray.size());
//int returnSizecount = stockList.getStocklst().size();
return 1;
}
The problem is that it giving me following error:
Could not write request: no suitable HttpMessageConverter found for request type [org.json.JSONArray].Any suggestion is greatly acceptable.
There are no MessageConverter for JSONArray, so I suggest do the following.
HttpEntity<JSONArray> entity = new HttpEntity<JSONArray>(jsonArray, headers);
Convert Class JSONArray to String, and add that to HttpEntity, you know use toString
java.lang.String toString()
Make a JSON text of this JSONArray.
HttpEntity entity = new HttpEntity(jsonArray.toString(), headers);
Or change to Jackson implementation Spring have support to that. XD
If you dont want to do the above, consider create your own implementation of messageConverter, that will work but is harder
update
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
headers.setContentType(MediaType.APPLICATION_JSON);
update 2 Change endpoint to.
#RequestMapping(value = "/testStock", method = RequestMethod.POST)
public #ResponseBody int testStock(#RequestBody String jsonArray) {
you need to have httpmessageconverter configured for your resttemplate, please read my post for configuring http message conveter for you webservice
http://stackoverflow.com/questions/19963127/new-to-spring-and-jackson-2-what-does-this-bean-declaration-allow-for-in-a-spri/19973636#19973636.
and for you problem to convert your http request to json you might add this entry in your restemplate configuration
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
The error is quite straightforward. You do not have a converter for the JSONArray. Converting the array to a String (using toString) did help you here, but there is a better way:
Just add a converter for the json.org objects:
Add this to your pom.xml
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-json-org</artifactId>
</dependency>
And then on your ObjectMapper add the JsonOrgModule:
mapper.registerModule(new JsonOrgModule());

Need help on RestTemplate Post Request with Body Parameters?

I have a rest api url and submitted the same as POST request with body (user name, password, other parameters) via Rest Client (restclient-ui-2.4-jar-with-dependencies) and it got worked fine without any issues.
Ex:
URL: https://test.com/cgi-bin/testing/api
Body: username=testuser&password=pass123&id=13002&name=raju
The same is not working fine when i used Spring RestTemplate postForObject(url, varmap, Employee.class) method.
Can someone help me with a simple example where the request is a URL, with body parameters and the response is XML which is mapped with a class?
Sample Code:
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("username", "test");
map.add("password", "test123");
map.add("id", "1234");
MarshallingHttpMessageConverter mc = new MarshallingHttpMessageConverter();
mc.setMarshaller(new Jaxb2Marshaller());
mc.setUnmarshaller(new Jaxb2Marshaller());
list.add(marshallingHttpMessageConverter);
emediateRestTemplate.setMessageConverters(list);
Employee employee = (Employee) restTemplate.postForObject(url, map, Employee.class);
Thanks in advance,
Kathir
The above converters Ex: "MarshallingHttpMessageConverter" are not required.
MultiValueMap<String, String> parametersMap = new LinkedMultiValueMap<String, String>();
parametersMap.add("username", "test");
parametersMap.add("password", "test123");
parametersMap.add("id", "1234");
For Post:
restTemplate.postForObject(url, parametersMap, Employee.class);
url is String - rest api URL
parametersMap - MultiValueMap
Employee - object which needs to be converted from the JSON response
For Get:
restTemplate.getForObject(url, class object, variablesMap);
url is : String - rest api URL
variablesMap - Map
class object - object which needs to be converted from the JSON response

Resources