Advertisement
Guest User

Untitled

a guest
Nov 12th, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package facades;
  7.  
  8. import java.io.IOException;
  9. import java.net.HttpURLConnection;
  10. import java.net.MalformedURLException;
  11. import java.net.URL;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. import java.util.Scanner;
  15. import java.util.concurrent.Callable;
  16. import java.util.concurrent.ExecutionException;
  17. import java.util.concurrent.ExecutorService;
  18. import java.util.concurrent.Executors;
  19. import java.util.concurrent.Future;
  20.  
  21. /**
  22. *
  23. * @author vince
  24. */
  25. public class DataFromSwapi {
  26. private static final Integer[] hostID = {1,2,3,4,5};
  27. private static final ExecutorService threadpool = Executors.newCachedThreadPool();
  28. private static List<Future<String>> futures = new ArrayList<>();
  29.  
  30. public DataFromSwapi() {
  31. }
  32.  
  33. public String getPeople() throws InterruptedException, ExecutionException{
  34. for (int i = 0; i < hostID.length; i++) {
  35. final int ID = hostID[i];
  36. Future<String> future = threadpool.submit(new Callable() {
  37. @Override
  38. public String call() throws Exception {
  39. return ID + "\t\tPerson:" + getSwappiData(ID);
  40. }
  41. });
  42. futures.add(future);
  43. }
  44.  
  45. for (Future<String> fut : futures) {
  46. System.out.println(fut.get());
  47. }
  48.  
  49. threadpool.shutdown();
  50.  
  51. return "";
  52. }
  53.  
  54.  
  55. public String getSwappiData(int id) throws MalformedURLException, IOException {
  56. URL url = new URL("https://swapi.co/api/people/" + id);
  57. HttpURLConnection con = (HttpURLConnection) url.openConnection();
  58. con.setRequestMethod("GET");
  59. con.setRequestProperty("Accept", "application/json;charset=UTF-8");
  60. con.setRequestProperty("User-Agent", "server"); //remember if you are using SWAPI
  61. Scanner scan = new Scanner(con.getInputStream());
  62. String jsonStr = null;
  63. if (scan.hasNext()) {
  64. jsonStr = scan.nextLine();
  65. }
  66. scan.close();
  67. return jsonStr;
  68. }
  69.  
  70.  
  71. public static void main(String[] args) throws InterruptedException, ExecutionException {
  72. DataFromSwapi swap = new DataFromSwapi();
  73.  
  74. swap.getPeople();
  75. }
  76.  
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement