Get value from response body in RestClient - spring

I am using Rest client of Firefox. I want to get value from response that is showing on Response body(Raw) in Rest-Client. I want to get this value in SpringBoot. Is it possible? If yes then How?
I have tried too many times but didn't get Satisfactory solution.

Using a Spring RestTemplate to make the calls will return a ResponseEntity. The simplest way to get the raw response would be this:
RestTemplate restTemplate = new RestTemplate();
try{
ResponseEntity<String> response = restTemplate.getForEntity(URI.create("http://example.org"),String.class);
System.out.println(response.getBody());
} catch (RestClientResponseException exception){
System.out.println(String.format("Error code %d : %s",e.getStatusCode().value(),e.getResponseBodyAsString()));
HttpHeaders errorHeaders = e.getResponseHeaders();
}
The ResponseEntity class will allow you to access the headers as well.
For more information on RestTemplate you can look at the docs here.

Related

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.

RestTemplate Exchange return Url Rejected

I'm facing a weird issue with an Api Call inside my spring boot application. When I use restTemplate to call an API :
ResponseEntity<String> response;
HttpHeaders headers = new HttpHeaders();
headers.set("X-Api-Key", "blablabla");
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity entity = new HttpEntity(headers);
try {
response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
} catch (HttpClientErrorException e) {
throw new HttpClientErrorException(e.getStatusCode());
}
I can't have any response of the called API. It always returns a 200 Http Status but the following body :
<200 OK,<html><head><title>Request Rejected</title></head><body>The requested URL was rejected. Please consult with your administrator.<br><br>Your support ID is: 6140245264157490471</body></html>,{Connection=[close], Cache-Control=[no-cache], Content-Type=[text/html; charset=utf-8], Pragma=[no-cache], Content-Length=[188]}>
I tried to call the API with the uri and headers used in my app in Postman and it works :/
I've already search for a similar issue in SOF and Google but can't find any response.
I hope someone will help me :D
Thx
I found the solution of the issue. It seems to be a bug of the company's firewall which catch this call as a threat ;)

301 ResponseCode in RestTemplate Client

I am trying to consume a service using RestTemplate in Spring. I tried around and each time getting 301 as response code. However, I am good to get a json response from the same uri while using POSTMAN.
Here is the code to get the statelist:
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
String baseUri = "http://www.whizapi.com/api/v2/util/ui/in/indian-states-list";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUri)
.queryParam("project-app-key","my-key");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> stats = restTemplate.exchange(builder.build().toUri(),
HttpMethod.GET,entity ,String.class);
Please suggest if I am missing anything.
HTTP 301 is a permanent redirect. You are accessing an outmoded url.
Having checked this url http://www.whizapi.com/api/v2/util/ui/in/indian-states-list redirected to https://www.whizapi.com/api/v2/util/ui/in/indian-states-list.ashx.
The same can be seen in Location response header as shown in the below image.
So, you should directly request https://www.whizapi.com/api/v2/util/ui/in/indian-states-list.ashx from your restTemplate object.
More details could be found here
Hope this helps!

Spring RestTemplate receives "401 Unauthorized"

I am using the following to retrieve JSON via RestTemplate in Spring 4:
protected DocInfoResponse retrieveData(String urlWithAuth) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + auth.getSig());
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<DocInfoResponse> response = restTemplate.exchange(urlWithAuth, HttpMethod.GET, request, DocInfoResponse.class);
return response.getBody();
}
I used the same code (with different response class) to successfully get a JSON doc from the same site (with different parameters to get a different doc).
When I execute the above code I receive the following stack trace (in part):
Caused by: org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
at
org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
Can anyone point me to why this might be receiving the exception?
I found that my issue originally posted above was due to double encryption happening on the auth params. I resolved it by using UriComponentsBuilder and explicitly calling encode() on the the exchange().
SyncResponse retrieveData(UriComponentsBuilder builder) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<SyncResponse> response = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET, request, SyncResponse.class);
return response.getBody();
}
My UriComponentsBuilder was built using:
UriComponentsBuilder buildUrl(String urlString) {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(urlString);
return auth.appendAuth(builder);
}
(The auth.appendAuth() adds additional .queryParams() needed by the target service in urlString.)
The call to execute this was retrieveData(buildUrl(urlString));.
After investigating on my own problem, I realized that FireFox RESTClient was successful because I was connected to the target URL. The Basic Auth I thought I was using, was not so basic after all.
Eventually, I read the doc of the app i was trying to connect to and realized they propose a connection token mechanism. Now it works.
After reading your code, I say it looks quite OK, although I'm not sure what is your object auth on which you call getSig.
First things first: try to access your service from any client, like a web browser, a PostMan or RESTClient. Make sure you successfully retrieve your infos WITHOUT being connected to your app!!!
Depending on the result, I say you should, either try to encrypt manually your Authorization token (you'll easilly find posts on this site to show you how to) or try another connection mechanism.
The process of creating the Authorization header is relatively straightforward for Basic Authentication, so it can pretty much be done manually with a few lines of code:
HttpHeaders createHeaders(String username, String password){
return new HttpHeaders() {{
String auth = username + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(Charset.forName("US-ASCII")) );
String authHeader = "Basic " + new String( encodedAuth );
set( "Authorization", authHeader );
}};
}
Then, sending a request becomes just as simple:
RestTemplate restTemplate = new RestTemplate();
restTemplate.exchange
(uri, HttpMethod.POST, new HttpEntity<T>(createHeaders(username, password)), clazz);
https://www.baeldung.com/how-to-use-resttemplate-with-basic-authentication-in-spring#manual_auth

perform a get request with spring rest template and check returned status code is ok

Its just submitting the sitemap to google so far i have
RestTemplate restTemplate = new RestTemplate();
HttpEntity<?> responseEntity = restTemplate.getForEntity("http://www.google.com/webmasters/tools/ping?sitemap={url}", String.class,"http://mySite.com/sitemap.txt);
How do I check the server HTTP status that is returned?
restTemplate.getForEntity(String, Class<T>, String...) returns a ResponseEntity<T> (extends HttpEntity), which has a method for retrieving the status code.
ResponseEntity.getStatusCode()
You should utilize that instead of HttpEntity.
You need to execute request and check response status.
Example code:
//when
ResponseEntity<Void> response = restTemplate.exchange(uri, HttpMethod.GET, HttpEntity.EMPTY, Void.class);
//then
assertEquals(HttpStatus.OK, response.getStatusCode());

Resources