Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package facades;
- import java.io.IOException;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Scanner;
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- /**
- *
- * @author vince
- */
- public class DataFromSwapi {
- private static final Integer[] hostID = {1,2,3,4,5};
- private static final ExecutorService threadpool = Executors.newCachedThreadPool();
- private static List<Future<String>> futures = new ArrayList<>();
- public DataFromSwapi() {
- }
- public String getPeople() throws InterruptedException, ExecutionException{
- for (int i = 0; i < hostID.length; i++) {
- final int ID = hostID[i];
- Future<String> future = threadpool.submit(new Callable() {
- @Override
- public String call() throws Exception {
- return ID + "\t\tPerson:" + getSwappiData(ID);
- }
- });
- futures.add(future);
- }
- for (Future<String> fut : futures) {
- System.out.println(fut.get());
- }
- threadpool.shutdown();
- return "";
- }
- public String getSwappiData(int id) throws MalformedURLException, IOException {
- URL url = new URL("https://swapi.co/api/people/" + id);
- HttpURLConnection con = (HttpURLConnection) url.openConnection();
- con.setRequestMethod("GET");
- con.setRequestProperty("Accept", "application/json;charset=UTF-8");
- con.setRequestProperty("User-Agent", "server"); //remember if you are using SWAPI
- Scanner scan = new Scanner(con.getInputStream());
- String jsonStr = null;
- if (scan.hasNext()) {
- jsonStr = scan.nextLine();
- }
- scan.close();
- return jsonStr;
- }
- public static void main(String[] args) throws InterruptedException, ExecutionException {
- DataFromSwapi swap = new DataFromSwapi();
- swap.getPeople();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement