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);
Related
I tried to access the API through feign client whose code is given below:
#PostMapping(value ="/ProfileManagement/CheckBeneExist" , produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<CheckBeneAlreadyExistResp> checkBeneAlreadyExist(#RequestHeader("Authorization") String bearerAuthHeader, CheckBeneAlreadyExistReq req);
It is not working and gave me an error. But when I created the restTemplate for this, it is working fine.
#Autowired
RestTemplate restTemplate;
#PostMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CheckBeneAlreadyExistResp> checkBeneAlreadyExist(String bearerAuthHeader,
CheckBeneAlreadyExistReq req){
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(bearerAuthHeader);
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<CheckBeneAlreadyExistReq> request = new HttpEntity<CheckBeneAlreadyExistReq>(req ,headers);
ResponseEntity<CheckBeneAlreadyExistResp> response = restTemplate.postForEntity( "example.com/UTLROnlineRemitAPI/ProfileManagement/CheckBeneExist", request , CheckBeneAlreadyExistResp.class );
System.out.println(response);
return response;
}
I am new to spring boot. Can someone tell where it gets wrong here.
This is the schema for which I have implement business logic
type Query {
getLicenseInformation(localmd5: String): License #aws_cognito_user_pools
getUserInformation(username: String!): CognitoUser #aws_iam
listUsers(searchString: String): [NamedResource] #aws_iam
}
I use RestTemplate as my Java client to consume graphql endpoint giving API key as authorization. I ad dthe api key in the header paart as x-api-key.
RestTemplate restTemplate=new RestTemplate();
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("x-api-key",api_key.getId());
requestHeaders.set("Content-Type","application/graphql");
HttpEntity entity = new HttpEntity(requestHeaders);
ResponseEntity<String> exchange = restTemplate.exchange(URL, HttpMethod.POST, new HttpEntity(query,requestHeaders),String.class);
The above implementation retrieves the values from the backend.
But according the schema which is defined by the other team, the authorization mode is not API key rather iam. So I have to configure the rest template accordingly.
Where in the Client side code in Java I can configure so that aws_iam is used as authorization method to retrieve the information from the endpoint. Dynamodb is the datasource
Building the request object like below helps:
private DefaultRequest prepareRequest(HttpMethodName method, InputStream content) {
Map<String,String> headers = new HashMap<>();
headers.put("Content-type", "application/json");
headers.put("type", "AUTH_TYPE.AWS_IAM");
headers.put("X-Amz-Security-Token",securityToken);
DefaultRequest request = new DefaultRequest(API_GATEWAY_SERVICE_NAME);
request.setHttpMethod(method);
request.setContent(content);
request.setEndpoint(this.endpoint);
request.setHeaders(headers);
return request;
}
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 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);
I want to perform a put request in Java Spring using rest template. I know how to do a regular request where the value looks like a traditional JSON:
{
"key":"value"
}
however i want to send the data as raw value:
foobar
At least in Postman that is what the data looks like in the raw option
How can this be emulated in Spring?
EDIT: Additional Info
Here is the code that I am currently using
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response =
restTemplate.exchange(url, HttpMethod.PUT, createHttpEntity(), String.class);
createHttpEntity() adds headers with appropriate authorization etc
The URL consumes a PUT request and accepts a singular link like so:
https://foobar.com
public HttpEntity createHttpEntity()
{
HttpHeaders headers = new HttpHeaders();
headers.set(Constants.AUTHORIZATION, Constants.BEARER + Base64.getEncoder().encodeToString(token.getBytes()));
headers.set(Constants.APP_ID_NAME, Constants.APP_ID);
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity( headers);
}
You need to set the Content-Type:text/plain in order to send plain text as a raw value in a request.
Original (wrong) answer:
Return a String (or whatever type of value you want to return) and annotate your method with #ResponseBody
Use this constructor for your HttpEntity instead.
HttpHeaders headers = new HttpHeaders();
// ...
return new HttpEntity<>("MY REQUEST BODY", headers);