How to call service in spring boot - spring

How can I call a service like the following in the spring-boot using the RestTemplate class ???
service api : https://192.168.100.20/api/index.php?e=/Base/User/Filter&apikey=a27209c3-edd6-6384-e1cb-1bef2df28&salt=1747229424&signature=JFH44DtCHdSV%2BJBvajNQBsiak07nPVyFb7ZYKj%2BqTno%3D

Something like this would work, but I'm not sure what exactly is your goal.
private RestTemplate template = new RestTemplate();
private String url = "https://192.168.100.20/api/index.php?e=/Base/User/Filter&apikey=a27209c3-edd6-6384-e1cb-1bef2df28&salt=1747229424&signature=JFH44DtCHdSV%2BJBvajNQBsiak07nPVyFb7ZYKj%2BqTno%3D";
template.getForEntity(url, String.class);

The first thing you should try to find is which Http Verb the service you want to call use.
GET, PUT, etc.
When you know which HTTP verb you have to use, you can use RestTemplate with the http verb of your service.
For GET
RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl =
"https://192.168.100.20/api/index.php?e=/Base/User/Filter&apikey=a27209c3-edd6-6384-e1cb-1bef2df28&salt=1747229424&signature=JFH44DtCHdSV%2BJBvajNQBsiak07nPVyFb7ZYKj%2BqTno%3D";
ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl, String.class);
For POST
RestTemplate restTemplate = new RestTemplate();
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class);

Related

TraceID for a request is not travelling between services

I am calling a microservice from a microservice and expecting the traceID (given by sleuth) initiated from base service should travel to the called services as implanted sleuth with zipkin.
Here is the call to the service
RestTemplate restTemplate = new RestTemplate();
logger.info("ApplicationController: controllerMessage() called: " + properties.getType() +
" " + properties2.getMode());
String uri = "http://localhost:8089/poc1/message";
//String uri = "http://google.com";
HttpHeaders headers = new HttpHeaders();
//headers.add("Authorization", authToken);
HttpEntity request = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.exchange(
uri,
HttpMethod.GET,
request,
String.class
);
Expecting that the same traceID printed in the logs of above service will be printed in the logs of called service. In this case, same trace id should print in the logs of http://localhost:8089/poc1/message. However this is not happening.
Using 2.7.5 version of spring boot and 2021.0.4 of spring cloud.
Any clue what is wrong here?
Expecting the same traceID generated by the initial request should print in the logs of called service.
You're creating RestTemplate via new. Please create it as a bean and inject it to your code.
#Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
We're writing it in the docs with a big exclamation mark here https://docs.spring.io/spring-cloud-sleuth/docs/current/reference/html/integrations.html#sleuth-http-client-rest-template-integration
Let me paste that for your convenience
You have to register RestTemplate as a bean so that the interceptors get injected. If you create a RestTemplate instance with a new keyword, the instrumentation does NOT work.

REST API call from spring boot not working

I am trying to fetch live data from NSE options trading. Below code is not working and the request made is stuck without any response.
Any workaround on this?
public void getLiveBankNiftyData() {
String RESOURCE_PATH = "https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY";
ResponseEntity<Object[]> responseEntity = restTemplate.getForEntity(RESOURCE_PATH, Object[].class);
Object[] objects = responseEntity.getBody();
}
i tried this
// request url
String url = "https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY";
// create an instance of RestTemplate
RestTemplate restTemplate = new RestTemplate();
// make an HTTP GET request
String json = restTemplate.getForObject(url, String.class);
// print json
System.out.println(json);
I found a way out. Instead of using RestTemplate I used WebClient and this solved the issue.

Could Not call Oauth 2 from RestTemplate

I tried to call oauth 2 using Spring RestTemplate but ended up with this error 404 Not Found: [{"message":"no Route matched with those values"}]
below is my code .OauthRequest is class created by me .
String oauthurl = serverurl + GET_TOKEN;
HttpHeaders headers = buildHeader();
OauthRequest oathRequest = new OauthRequest();
oathRequest.setClient_id(clientid);
oathRequest.setClient_secret(clientsecret);
oathRequest.setAuthenticated_userid(usercode);
oathRequest.setScope(scope);
oathRequest.setGrant_type(grantTypePassword);
oathRequest.setProvision_key(key);
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Host", hostname);
headers.set("Accept-Version", "1.0");
headers.set("Content-Length", MAX_TRANSFER_SIZE);
HttpEntity<OauthRequest> requestEntity = new HttpEntity<>(oathRequest, headers);
ResponseEntity<OauthResponse> result = restTemplate.exchange(oauthurl, HttpMethod.POST, requestEntity,
OauthResponse.class);
return result.getBody();
Is there any limitation on calling from RestTemplate rather than using OAuth2RestTemplate .My understanding is it will be achievable using RestTemplate also.Must i use OAuth2RestTemplate ?Any help?
RestTemplate does not set hostname in
headers.set("Host", hostname);
Adding below it worked
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");

413 request entity too large issue in HTTP Get method call

Please don't mistake it as already asked question. The main difference here is, this issue is coming in Get method call. All the solutions discussed here or other places talks about either POST method or multipart form data.
Configuration I have provided is as below:
String url = env.getProperty(ApplicationConstants.PMCC_MANAGER_REGION_QUERY_URL);
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url).queryParam("inTIS_PMA_NUMBER","ALL");
URI uri = builder.build().toUri();
RestTemplate restTemplate = getRestTemplateBuilder().build();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
private RestTemplateBuilder getRestTemplateBuilder() {
Integer connectionTimeOut = 2000;
Integer readTimeOut = 3000;
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
restTemplateBuilder.setConnectTimeout(connectionTimeOut);
restTemplateBuilder.setReadTimeout(readTimeOut);
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setBufferRequestBody(false);
restTemplateBuilder.requestFactory(factory);
return restTemplateBuilder;
}
This code is part of Spring Boot application and deployed in WebLogic server.

spring boot application periodic post request via resttemplate in json

Below is my spring boot code snippet to post json data to server url every few min to tell that I am alive and running(which loads my json input data to db). purpose of this post request is to update the status on application monitoring tool.
What could be the right approach to implment this behaviour in my spring boot app? Is their any decorator api to do such post request to url, every few miuntes through out the application.? how can I know the time of successful post request to do next post request ? Please help me. Thanks in advance.
RestTemplate restTemplate = new RestTemplate();
String url = "endpoint url";
String requestJson = "{\"I am alive\":\"App name?\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String answer = restTemplate.postForObject(url, entity, String.class);
System.out.println(answer);
Why don't you use the #Scheduled annotation? This will seutes.nd your REST request every 3 minutes...
#Component
public class Heartbeater {
#Scheduled(fixedDelay = 180000)
public void heartbeat() {
// Your code is below...
RestTemplate restTemplate = new RestTemplate();
String url = "endpoint url";
String requestJson = "{\"I am alive\":\"App name?\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String answer = restTemplate.postForObject(url, entity, String.class);
System.out.println(answer);
}

Resources