Created
June 25, 2019 07:49
-
-
Save hadihammurabi/aceef4620b07cc9596627a573ccc494d to your computer and use it in GitHub Desktop.
Example for simple HTTP Request in Java
This file contains hidden or 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 org.json.JSONArray; | |
import org.json.JSONObject; | |
import org.json.JSONTokener; | |
import java.net.URL; | |
import java.net.HttpURLConnection; | |
import java.io.BufferedReader; | |
import java.io.InputStreamReader; | |
public class HTTPRequest { | |
public static void main(String[] args) { | |
try { | |
URL api = new URL("https://jsonplaceholder.typicode.com/users"); | |
HttpURLConnection connection = (HttpURLConnection) api.openConnection(); | |
connection.setRequestMethod("GET"); | |
BufferedReader buffer = new BufferedReader(new InputStreamReader(connection.getInputStream())); | |
String chunk; | |
StringBuffer content = new StringBuffer(); | |
while((chunk = buffer.readLine()) != null) { | |
content.append(chunk); | |
} | |
buffer.close(); | |
connection.disconnect(); | |
JSONTokener token = new JSONTokener(content.toString()); | |
JSONArray ob = new JSONArray(token); | |
for(int i=0; i < ob.length(); ++i) { | |
JSONObject it = ob.getJSONObject(i); | |
System.out.print(it.getString("name")); | |
System.out.println(" <" + it.getString("email") + ">"); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment