Created
June 28, 2019 03:53
-
-
Save hadihammurabi/57fcdfec733d55b913238322217904f8 to your computer and use it in GitHub Desktop.
Getting data from Rest API Server with concurrency
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.Runnable; | |
import java.net.URL; | |
import java.net.HttpURLConnection; | |
import java.io.BufferedReader; | |
import java.io.InputStreamReader; | |
class DataCollector implements Runnable { | |
StringBuffer result; | |
public void run() { | |
try { | |
URL url = new URL("https://jsonplaceholder.typicode.com/users/1"); | |
HttpURLConnection con = (HttpURLConnection) url.openConnection(); | |
con.setRequestMethod("GET"); | |
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); | |
String inputLine; | |
StringBuffer content = new StringBuffer(); | |
while ((inputLine = in.readLine()) != null) { | |
content.append(inputLine); | |
} | |
this.result = content; | |
in.close(); | |
} catch(Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
StringBuffer showResult() { | |
return result; | |
} | |
} | |
class LoadingScreen implements Runnable { | |
public void run() { | |
System.out.println("Loading..."); | |
} | |
} | |
public class GetAPI { | |
public static void main(String[] args) throws Exception { | |
DataCollector dataCollector = new DataCollector(); | |
Thread dataCollectorThread = new Thread(dataCollector); | |
dataCollectorThread.start(); | |
(new Thread(new LoadingScreen())).start(); | |
dataCollectorThread.join(); | |
System.out.println(dataCollector.showResult()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment