-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathJava_GET_POST.java
75 lines (69 loc) · 2.81 KB
/
Java_GET_POST.java
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
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
public class HTTPGETPOST {
public static void main(String[] args) throws Exception {
get();
post();
}
public static void get() throws Exception
{
// TODO Auto-generated method stub
URL urlForGetRequest = new URL("http://dummy.restapiexample.com/api/v1/employees");
String readLine = null;
HttpURLConnection conection = (HttpURLConnection) urlForGetRequest.openConnection();
conection.setRequestMethod("GET");
//conection.setRequestProperty("userId", "a1bcdef"); // set userId its a sample here
int responseCode = conection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(
new InputStreamReader(conection.getInputStream()));
StringBuffer response = new StringBuffer();
while ((readLine = in .readLine()) != null) {
response.append(readLine);
} in .close();
// print result
System.out.println("GET Result : " + response.toString());
//GetAndPost.POSTRequest(response.toString());
} else {
System.out.println("GET NOT WORKED");
}
}
public static void post() throws Exception
{
final String POST_PARAMS = "{\n" + "\"userId\": 101,\r\n" +
" \"id\": 101,\r\n" +
" \"title\": \"Test Title\",\r\n" +
" \"body\": \"Test Body\"" + "\n}";
System.out.println(POST_PARAMS);
URL obj = new URL("https://jsonplaceholder.typicode.com/posts");
HttpURLConnection postConnection = (HttpURLConnection) obj.openConnection();
postConnection.setRequestMethod("POST");
postConnection.setRequestProperty("userId", "a1bcdefgh");
postConnection.setRequestProperty("Content-Type", "application/json");
postConnection.setDoOutput(true);
OutputStream os = postConnection.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
int responseCode = postConnection.getResponseCode();
System.out.println("POST Response Code : " + responseCode);
System.out.println("POST Response Message : " + postConnection.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_CREATED) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
postConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in .readLine()) != null) {
response.append(inputLine);
} in .close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST NOT WORKED");
}
}
}