-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonjava.java
More file actions
70 lines (64 loc) · 2.21 KB
/
Jsonjava.java
File metadata and controls
70 lines (64 loc) · 2.21 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
65
66
67
68
69
70
package com.company;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
private static HttpURLConnection connection;
public static void main(String[] args) throws IOException {
// method1 java.net.httpConnection
BufferedReader reader;
String line;
StringBuffer respondContent=new StringBuffer();
try {
URL url = new URL("https://jsonplaceholder.typicode.com/albums");
connection = (HttpURLConnection) url.openConnection();
//request setup
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int status=connection.getResponseCode();
System.out.println(status);
if(status>299)
{
reader=new BufferedReader(new InputStreamReader(connection.getErrorStream()));
while ((line=reader.readLine())!=null)
{
respondContent.append(line);
}
reader.close();
}
else
{
reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line=reader.readLine())!=null)
{
respondContent.append(line);
}
reader.close();
}
//System.out.println(respondContent.toString());
parse(respondContent.toString());
}
catch (Exception e){
e.printStackTrace();
}
finally {
connection.disconnect();
}
}
public static String parse(String respondBody){
JSONArray albums=new JSONArray(respondBody);
for(int i=0; i<albums.length();i++){
JSONObject album=albums.getJSONObject(i);
int id=album.getInt("id");
int userId=album.getInt("userId");
String title=album.getString("title");
System.out.println(id+" "+userId+" "+title);
}
return null;
}
}