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.
Related
i have problem with api from dhl, i create GET api from dhl, when print in console, result will print, but when using browser i got response like this :
com.squareup.okhttp.internal.http.RealResponseBody#68bd3d26
this my code :
#RequestMapping("/getData")
public String getAcc() throws IOException
{
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
HttpUrl httpUrl = new HttpUrl.Builder()
.scheme("https")
.host("api-eu.dhl.com")
.addPathSegment("track")
.addPathSegment("shipments")
.addQueryParameter("trackingNumber", "cencored")
.addQueryParameter("service", "express")
.build();
Request request = new Request.Builder()
.addHeader("content-type", "application/json")
.addHeader("Connection", "close")
.addHeader("DHL-API-Key", "cencored")
.addHeader("ConsumerKey", "cencored")
.addHeader("ConsumerSecret", "cencored")
.removeHeader("Content-Encoding")
.removeHeader("Content-Length")
.url(httpUrl) // <- Finally put httpUrl in here
.build();
response = client.newCall(request).execute();
System.out.println(response.body().string());
return this.response.body().toString();
}
solved...
this is weird, but work for me.
so we can't call "response.body().string();" twice.
This is the correctly way to consume a soap webservice with spring boot: https://spring.io/guides/gs/consuming-web-service/
Follow this tutorial and it works fine.
Right now, I have a class Message representing a JSON object as so
#Value
#Builder
public class Message {
#JsonProperty("#msgType")
String msgType;
#JsonProperty("#type")
String type;
String category;
#Singular("characteristic") List<CharacteristicItem> characteristic;
#Singular("receiver") List<ReceiverItem> receiver;
Sender sender;
}
I would like to send an instance of the class Message as a JSON to remote URL https:example.com/message. How can I create a method that can POST to this URL with the JSON? Note, I am not creating a mapping, I just want to POST to URL and retrieve the HTTP response and convert to string. I'm thinking of using WebClient. Note, I am only interested in seeing if the response is 200, 400, etc., I don't need to handle the response JSON.
If you want to use WebClient you can write below code to post JSON data to URL and retrieve response status code.
WebClient client = WebClient.builder()
.baseUrl("https://example.com")
.build();
Message m = Message.builder().build();
Mono<HttpStatus> httpStatusMono = client.post().uri("/createMessage")
.body(Mono.just(m), Message.class)
.exchange().map(r -> r.statusCode());
// s.value() will give you response status code
httpStatusMono.subscribe(s -> s.value());
If you dont wan't to use WebClient another alternative is RestTemplate
below is the code to achieve the same thing with RestTemplate
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
ResponseExtractor<Integer> responseExtractor = clientHttpResponse -> {
return Integer.valueOf(clientHttpResponse.getStatusCode().value());
};
Message m = Message.builder().build();
RequestCallback requestCallback = clientHttpRequest -> {
objectMapper.writeValue(clientHttpRequest.getBody(), m);
};
Integer status = restTemplateBuilder.build()
.execute("https://example.com/createMessage",
HttpMethod.POST, requestCallback, responseExtractor);
System.out.println(status);
I'm trying to POST a multipart/form-data using Spring RestTemplate with a byte array as the file to upload and it keeps failing (Server rejects with different kinds of errors).
I'm using a MultiValueMap with ByteArrayResource. Is there something I'm missing?
Yes there is something missing.
I have found this article:
https://medium.com/#voziv/posting-a-byte-array-instead-of-a-file-using-spring-s-resttemplate-56268b45140b
The author mentions that in order to POST a byte array using Spring RestTemplate one needs to override getFileName() of the ByteArrayResource.
Here is the code example from the article:
private static void uploadWordDocument(byte[] fileContents, final String filename) {
RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl = "http://localhost:8080/spring-rest/foos"; // Dummy URL.
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("name", filename);
map.add("filename", filename);
// Here we
ByteArrayResource contentsAsResource = new ByteArrayResource(fileContents) {
#Override
public String getFilename() {
return filename; // Filename has to be returned in order to be able to post.
}
};
map.add("file", contentsAsResource);
// Now you can send your file along.
String result = restTemplate.postForObject(fooResourceUrl, map, String.class);
// Proceed as normal with your results.
}
I tried it and it works!
I added an issue to send a request from java client to Python service in FastApi and sending a ByteArrayResource instaead of simple byte[] fixed the issue.
FastAPI server returned: "Expected UploadFile, received: <class 'str'>","type":"value_error""
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);
}
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.