Skip to content

Instantly share code, notes, and snippets.

@m1k3yfoo
Last active September 30, 2018 22:57
Show Gist options
  • Save m1k3yfoo/ba24d3a3429cd098985bf0323cbf9f15 to your computer and use it in GitHub Desktop.
Save m1k3yfoo/ba24d3a3429cd098985bf0323cbf9f15 to your computer and use it in GitHub Desktop.
[Java Spring Boot] Consume REST API #SpringBoot
package com.example.project;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class NewsController {
public News getNews() throws Exception{
JSONObject news = new JSONObject();
String getUrl = "https://api.nytimes.com/svc/topstories/v2/home.json?ef00222412e043fc8c50c9b6c2bdeceb";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<Map> topStories = restTemplate.exchange(getUrl, HttpMethod.GET, entity, Map.class);
if (topStories.getStatusCode() == HttpStatus.OK) {
news = new JSONObject(topStories.getBody());
}
return news;
}
}
@SpringBootApplication
public class RestBooksApi {
static RestTemplate restTemplate;
public RestBooksApi() {
restTemplate = new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RestBooksApi.class, args);
try {
JSONObject books = getEntity();
System.out.println(books);
} catch (Exception e) {
e.printStackTrace();
}
}
public static JSONObject getEntity() throws Exception {
JSONObject books = new JSONObject();
String getUrl = "https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<Map> bookList = restTemplate.exchange(getUrl, HttpMethod.GET, entity, Map.class);
if (bookList.getStatusCode() == HttpStatus.OK) {
books = new JSONObject(bookList.getBody());
}
return books;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment