-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientGet.java
More file actions
100 lines (80 loc) · 2.99 KB
/
Copy pathClientGet.java
File metadata and controls
100 lines (80 loc) · 2.99 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package com.app.client;
import com.app.Token;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
*
* @author Felipe L. Garcia
*/
public class ClientGet {
private static String urlPolls = "http://localhost:8084/apipolls/polls";
public static void main(String[] args) {
// String output = getURL();
// System.out.println(output);
//
// String output = getQuestion(1);
// System.out.println(output);
//
String output = getQuestionPage(0);
System.out.println(output);
}
public static String getURL() {
return restPolls(urlPolls, null,null);
}
public static String getQuestion(int id) {
Token token = ClientPost.getToken("usuario", "senha");
if (token == null) {
return null;
}
String url = urlPolls+"/questions/" + id;
return restPolls(url, null,token.getAccess_token());
}
public static String getQuestionPage(int page) {
Token token = ClientPost.getToken("usuario", "senha");
if (token == null) {
return null;
}
String url = urlPolls+"/questions"+(page>0
?"?page="+page
:"");
return restPolls(url, null,token.getAccess_token());
}
private static String restPolls(String urlGet,String input,String token) {
System.out.println(urlGet);
// http://localhost:8080/RESTfulExample/json/product/get
try {
URL url = new URL(urlGet);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
//Authorization
if(token!=null && !token.trim().isEmpty()){
conn.setRequestProperty("Authorization", "token "+token);
}
if(input!=null && !input.trim().isEmpty()){
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
}
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output = "";
String read;
while ((read = br.readLine()) != null) {
output += read;
}
conn.disconnect();
return output;
} catch (Exception e) {
System.out.println(e);
}
return null;
}
}