I am using Spring's RestTemplate to send a POST request to my RestController with request parameters and a request header.
It fails with this error message: POST request for "[myurl]" resulted in 404 (null); invoking error handler.
Note that "[myurl]" is "http://localhost:8080/test"
This is my code:
RestTemplate rest = new RestTemplate();
MultiValueMap<String, Integer> map = new LinkedMultiValueMap<String, Integer>();
map.add("num1", 1);//request parameters
map.add("num2", 2);
HttpHeaders headers = new HttpHeaders();//request header
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<MultiValueMap<String, Integer>> request = new HttpEntity<MultiValueMap<String, Integer>>(map, headers);
Object obj = rest.postForObject("[myurl]", request, Object.class);
logger.log("Returned object: " + obj.toString());
Maybe try doing something like (if you can get away with MultiValueMap):
RestTemplate rest = new RestTemplate();
Map<String, Integer> map = new HashMap<>();
map.put("num1", 1);//request parameters
map.put("num2", 2);
Object obj = rest.postForObject("[myurl]", map, Object.class);
logger.log("Returned object: " + obj.toString());
Related
My rest endpoint:
#PostMapping("/customerPolicyInfo")
public Map<String, Object> getCustomerPolicyInfo(#RequestParam String policyNumber, #RequestParam Claims authenticatedUserDetails) {
}
How to call this endpoint from another service using RestTemplate? It is a HTTP POST request?
My current code where I am calling this above endpoint looks like this:
Claims authenticatedUserDetails = (Claims) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// create a map for post parameters
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("policyNumber", policyNumber);
map.add("authenticatedUserDetails", authenticatedUserDetails.toString());
// build the request
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map, headers);
// send POST request
ResponseEntity<Map> response = null;
try {
response = restTemplate.postForEntity("http://localhost:8081/policy-service/customerPolicyInfo", entity, Map.class);
} catch (RestClientException e) {
e.printStackTrace();
}
return response.getBody();
I have a rest Controller where i am trying to get the Token from a service using the RestTemplate in Spring Boot. The application works fine when i use Postman but from Java Application i get 400 Bad Request.
My Java Sample :
#PostMapping("/service")
private String generateAuthenticationToken() {
HttpHeaders authenticationTokenHeaders = new HttpHeaders();
authenticationTokenHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
JSONObject sfmcBUCredential = new JSONObject();
JSONObject sfmcTokenResponseObject;
sfmcBUCredential.put("grant_type", sfmcConfig.getGrant_type());
sfmcBUCredential.put("client_id", sfmcConfig.getClient_id());
sfmcBUCredential.put("client_secret", sfmcConfig.getClient_secret());
String sfmcBUCredentialString = sfmcBUCredential.toString();
System.out.println("Values before sending to POST Request are :::" + sfmcBUCredentialString);
HttpEntity<String> getTokenEntity = new HttpEntity<>(sfmcBUCredentialString, authenticationTokenHeaders);
System.out.println("Values after sending to POST Request are :::" + getTokenEntity.toString());
System.out.println("URL is :::" + GET_SFMC_ENDPOINT_URL);
//String tokenResponse = restTemplate.postForObject(GET_SFMC_ENDPOINT_URL, getTokenEntity, String.class);
ResponseEntity<String> tokenResponse = restTemplate.exchange(GET_SFMC_ENDPOINT_URL, HttpMethod.POST, getTokenEntity, String.class);
sfmcTokenResponseObject = new JSONObject(tokenResponse.getBody());
System.out.println("tokenResponse::::::::" + sfmcTokenResponseObject.getString("access_token").toString());
return sfmcTokenResponseObject.getString("access_token");
}
Logs :
Values before sending to POST Request are :::{"grant_type":"client_credentials","client_secret":"c1ae4b4a-498e-46a0-a02e-cd2378cb8db6","client_id":"Y43iLAhr4e0SoJ9KkV4vLKnGhNmS1Y3c"}
Values after sending to POST Request are :::<{"grant_type":"client_credentials","client_secret":"c1ae4b4a-498e-46a0-a02e-cd2378cb8db6","client_id":"Y43iLAhr4e0SoJ9KkV4vLKnGhNmS1Y3c"},[Content-Type:"application/x-www-form-urlencoded"]>
URL is :::https://keycloak.lab.hci.aetna.com/auth/realms/master/protocol/openid-connect/token
Try something like this:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("grant_type", sfmcConfig.getGrant_type());
map.add("client_id", sfmcConfig.getClient_id());
map.add("client_secret", sfmcConfig.getClient_secret());
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
ResponseEntity<LabelCreationResponse> response =
restTemplate.exchange("url",
HttpMethod.POST,
entity,
String.class);
I'm new to Spring and trying to do a rest request with RestTemplate. The Java code should do the same as below curl command:
curl --data "name=feature&color=#5843AD" --header "PRIVATE-TOKEN: xyz" "https://someserver.com/api/v3/projects/1/labels"
But the server rejects the RestTemplate with a 400 Bad Request
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("PRIVATE-TOKEN", "xyz");
HttpEntity<String> entity = new HttpEntity<String>("name=feature&color=#5843AD", headers);
ResponseEntity<LabelCreationResponse> response = restTemplate.exchange("https://someserver.com/api/v3/projects/1/labels", HttpMethod.POST, entity, LabelCreationResponse.class);
Can somebody tell me what I'm doing wrong?
I think the problem is that when you try to send data to server didn't set the content type header which should be one of the two: "application/json" or "application/x-www-form-urlencoded" . In your case is: "application/x-www-form-urlencoded" based on your sample params (name and color). This header means "what type of data my client sends to server".
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("PRIVATE-TOKEN", "xyz");
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("name","feature");
map.add("color","#5843AD");
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
ResponseEntity<LabelCreationResponse> response =
restTemplate.exchange("https://foo/api/v3/projects/1/labels",
HttpMethod.POST,
entity,
LabelCreationResponse.class);
You need to set the Content-Type to application/json. Content-Type has to be set in the request. Below is the modified code to set the Content-Type
final String uri = "https://someserver.com/api/v3/projects/1/labels";
String input = "US";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("PRIVATE-TOKEN", "xyz");
HttpEntity<String> request = new HttpEntity<String>(input, headers);
ResponseEntity<LabelCreationResponse> response = restTemplate.postForObject(uri, request, LabelCreationResponse.class);
Here, HttpEntity is constructed with your input i.e "US" and with headers.
Let me know if this works, if not then please share the exception.
Cheers!
It may be a Header issue check if the header is a Valid header, are u referring to "BasicAuth" header?
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED.toString());
headers.add("Accept", MediaType.APPLICATION_JSON.toString()); //Optional in case server sends back JSON data
MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<String, String>();
requestBody.add("name", "feature");
requestBody.add("color", "#5843AD");
HttpEntity formEntity = new HttpEntity<MultiValueMap<String, String>>(requestBody, headers);
ResponseEntity<LabelCreationResponse> response =
restTemplate.exchange("https://example.com/api/request", HttpMethod.POST, formEntity, LabelCreationResponse.class);
my issue, the MessageConverters contains other converters may converts then entity to json (like FastJsonHttpMessageConverter). So i added the FormHttpMessageConverter to ahead and it works well.
<T> JuheResult<T> postForm(final String url, final MultiValueMap<String, Object> body) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
return exchange(url, HttpMethod.POST, requestEntity);
}
<T> JuheResult<T> exchange(final String url, final HttpMethod method, final HttpEntity<?> requestEntity) {
ResponseEntity<JuheResult<T>> response = restTemplate.exchange(url, method, requestEntity,
new JuheResultTypeReference<>());
logger.debug("调用结果 {}", response.getBody());
return response.getBody();
}
public JuheSupplierServiceImpl(RestTemplateBuilder restTemplateBuilder) {
Duration connectTimeout = Duration.ofSeconds(5);
Duration readTimeout = Duration.ofSeconds(5);
restTemplate = restTemplateBuilder.setConnectTimeout(connectTimeout).setReadTimeout(readTimeout)
.additionalInterceptors(interceptor()).build();
restTemplate.getMessageConverters().add(0, new FormHttpMessageConverter());
}
fastjson prevent resttemplate converting other mediaTypes other than json
I try to send the shipping status from my database to ecommerce website, but I get:
400 bad request error.
Does anyone have any ideas?
HashMap orderItems = new HashMap<String, String>();
orderItems.put("id","558443685");
ArrayList<HashMap<String,String>> orderItemsArray = new ArrayList<HashMap<String,String>>();
orderItemsArray.add(orderItems);
HashMap contentOrderFulfillment = new HashMap<String, Object>();
contentOrderFulfillment.put("tracking_number", null);
contentOrderFulfillment.put("line_items",orderItemsArray);
HashMap orderFulfillment = new HashMap<String, Object>();
orderFulfillment.put("fulfillment", contentOrderFulfillment);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.add("X-ABC-Access-Token", "9a4d5c56a7edf1ac5bb17aa1c");
headers.add("Content-Type", MediaType.APPLICATION_JSON.toString());
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<String, Object>();
requestBody.add("fulfillment", orderFulfillment);
HttpEntity formEntity = new HttpEntity<MultiValueMap<String, Object>>(requestBody, headers);
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
ResponseEntity<String> responseEntity = restTemplate.exchange("https://mysite.abc.com/admin/orders/406287121/fulfillments.json",HttpMethod.POST, formEntity,String.class);
System.out.println("Response="+responseEntity.getBody());
400 response can be caused from many problems inside your request. Wrong parameters or something like that. Try the request first from command line - with curl or something. When you see it working check if the request from java has the exact same parameters sent.
Have a look in ResponseEntityExceptionHandler (or any descendant) if you extend that handler.
Most of the methods of the handler don't include a message body, so a solution would be for you to extend that class, override the methods handling the exceptions you would like to get an error message for, and provide message body to the handleExceptionInternal(..) method.
See also:
http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/
https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
I am triggering a GET request and getting the JSON data successfully via Spring RestTemplate. I also want to get the Response Header information but I am not sure how to get it.
private String getAPIKeySpring() {
RestTemplate restTemplate = new RestTemplate();
String url = baseURL+"/users/apikey";
Map<String, String> vars = new HashMap<String, String>();
vars.put("X-Auth-User", apiUser);
JsonVO jsonVO = restTemplate.getForObject(url, JsonVO.class, vars);
System.out.println(jsonVO);
return null;
}
ResponseEntity<JsonVO> responseEntity = restTemplate.getForEntity(url, JsonVO.class, vars);
JsonVO jsonVO = responseEntity.getBody();
HttpHeaders headers = responseEntity.getHeaders(); //<-- your headers