I have to call a PUT method using Resttemplate. I am able to hit the service from POST Man. But when i try the same request from Java using Resttemplate its throwing error .What could be mistake i am doing.
405 : [{"category":"ACCESS","code":"METHOD_NOT_SUPPORTED","description":"Request method 'PUT' not
supported","httpStatusCode":"405"}]
#Autowired
#Qualifier("orderMasterUpdateClient")
private RestTemplate orderMasterUpdateClient; // Loading the template with credentials and URL
ResponseEntity<SalesOrderDocument> responseEntity = orderMasterUpdateClient.exchange(
URL,
HttpMethod.PUT,
new HttpEntity<>(headers),
SalesOrderDocument.class, changeRequest);
If you want to send changeRequestobject data in the body of the PUT request, I suggest you to use next RestTemplate exchange method call:
String url = "http://host/service";
ChangeRequest changeRequest = new ChangeRequest();
HttpHeaders httpHeaders = new HttpHeaders();
HttpEntity<ChangeRequest> httpEntity = new HttpEntity<>(changeRequest, httpHeaders);
ResponseEntity<ChangeRequest> response = restTemplate
.exchange(url, HttpMethod.PUT, httpEntity, ChangeRequest.class);
Related
I have an REST API which accepts request headers in request. My controller is internally calling another API. What i want to do is pass all headers that i am getting in request to internal API that controller is calling.
I know that i can iterate over header and set them in HttpRequest that I am creating but is there any other way to set in a single step.
Thanks,
You can set headers as below :-
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("custom-header-name, "value");
HttpEntity<Request> entity = new HttpEntity<Request>(request, headers);
RestTemplate template = new RestTemplate();
ResponseEntity<Response> respEntity = template
.exchange("URL", HttpMethod.POST, entity , RestResponse.class);
I'm trying to create test unit for GET method which requires JSON payload to get result based on provided data in JSON.
I have tried that:
User user = new User();
user.setUserId(userId);
ResponseEntity<User> getResponse = restTemplate.exchange(getRootUrl() + "/getUser", HttpMethod.GET, user, User.class);
assertNotNull(getResponse);
assertEquals(getResponse.getStatusCode(), HttpStatus.OK);
but it throws an error on exchange for user that object is not suitable.
the method documentation is pretty straightforward
Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns the response as ResponseEntity.
URI Template variables are expanded using the given URI variables, if any.
Specified by:
exchange in interface RestOperations
Parameters:
url - the URL
method - the HTTP method (GET, POST, etc)
requestEntity - the entity (headers and/or body) to write to the request may be null)
responseType - the type of the return value
uriVariables - the variables to expand in the template
you need change user to HttpEntity
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
JSONObject parm = new JSONObject();
parm.put("user", user);
HttpEntity<JSONObject> entity = new HttpEntity<JSONObject>(parm, headers);
I'm trying to consume a rest service with authorization using the below code. I'm getting Status Code 200 with 404 result. The same params execute correctly via Postman. Can you please advise what to fix?
#Test
public void addEnterpriseTest() {
HttpHeaders headers1 = new HttpHeaders();
headers1.put("Authorization", Arrays.asList("Bearer 123"));
headers1.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
String uri = PROVISIONING_END_POINT + "enterprises";
RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> entity = new HttpEntity<>("Id=8888&Name=MyEnperprise", headers);
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST, entity, String.class);
System.out.println(result.getStatusCode()); //getting 200
System.out.println(result); //getting 404
}
I'm completely new to Java and trying to consume a rest API with Spring Boot in Gradle, so far I've managed to make a very basic get request to display a message like below
#RestController
public class HelloController {
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("message", "Hello");
return "hello";
}
}
Now, how to extend this get request to make HTTP requests consume an endpoint based on RestTemplate, assuming this is my endpoint that i want to consume like below:
RestTemplate restTemplate = new RestTemplate(); ResponseEntity response = restTemplate.getForEntity("http://aws.services.domain.com/country/id", String.class);
Finally, I want to achieve authorized HTTP GET requests by adding a token Bearer in the Authorization header.
Thank you for answers and suggestions in advance
If you want to add a header, you have to use exchange or execute method.
So, in your case:
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Your Bearer Token");
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.exchange(
url, HttpMethod.GET, entity, String.class, param);
I have a requirement where i need to call my spring batch application externally and not use the by default spring batch admin UI.
This is the url which i am hitting
http://localhost:8080/sample-batch-app/jobs/sampleJob.json?jobParameters=filename=C:\\Users\\test\\Documents\\test1\\WIP\\test2\\sample\\cvs\\process\\08242016\\failure\\sample.csv,fileavailable=true,run_date=2016/09/05,external=true
Using the below code
String url = postUrl;
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String json ="sample";
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
logger.debug("==Json sent to microservice==== "+json);
HttpEntity<String> requestEntity = new HttpEntity<String>(json, requestHeaders);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity,String.class);
logger.debug("RESTServiceUtils.executePost-->===========Ends"+response.getStatusCode());
if(response.getStatusCode()!=null && !response.getStatusCode().equals(HttpStatus.ACCEPTED)){
logger.info("Response is::============" + response.getBody());
}
But when i check the logs , all the // and \ in the url gets removed as a result the file is not getting processed.
The sample url i hit from postman api it works fine.
Kindly help.