-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.java
More file actions
65 lines (55 loc) · 2.36 KB
/
test.java
File metadata and controls
65 lines (55 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import net.sf.json.JSON;
import org.json.simple.*;
import org.json.simple.parser.JSONParser;
import org.jsoup.Jsoup;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class test {
public static List<User> getAllUsers(){
List<User> userList = new ArrayList<>();
//inline will store the JSON data streamed in string format
String inline = "";
try {
URL url = new URL("https://api.github.com/users");
//Parse URL into HttpURLConnection in order to open the connection in order to get the JSON data
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Set the request to GET or POST as per the requirements
conn.setRequestMethod("GET");
//Use the connect method to create the connection bridge
conn.connect();
//Get the response status of the Rest API
int responsecode = conn.getResponseCode();
System.out.println("Response code is: " + responsecode);
//Iterating condition to if response code is not 200 then throw a runtime exception
//else continue the actual process of getting the JSON data
if (responsecode != 200)
throw new RuntimeException("HttpResponseCode: " + responsecode);
else {
//Scanner functionality will read the JSON data from the stream
Scanner sc = new Scanner(url.openStream());
while (sc.hasNext()) {
inline += sc.nextLine();
}
System.out.println("\nJSON Response in String format");
sc.close();
}
JSONParser jsonParser = new JSONParser();
JSONArray users_list = (JSONArray) jsonParser.parse(inline);
ArrayList<JSONObject> users = new ArrayList<>();
for (int i = 0; i < users_list.size(); i++) {
users.add((JSONObject) users_list.get(i));
}
for (int i = 0; i < users.size(); i++) {
User user = new User((String) users.get(i).get("login"));
userList.add(user);
}
} catch (Exception e) {
e.printStackTrace();
}
return userList;
}
}