· 6 years ago · Dec 04, 2019, 07:24 PM
1package getpost;
2
3import java.io.BufferedReader;
4import java.io.IOException;
5import java.io.InputStreamReader;
6import java.io.OutputStream;
7import java.net.HttpURLConnection;
8import java.net.URL;
9
10public class glass {
11 public static void MyGETRequest() throws IOException {
12
13 URL urlForGetRequest = new URL("https://api.megaventory.com/v2017a/APIkey/APIkeyGet?APIKEY=59a80b0f6999f7a5%40m103546");
14 String readLine = null;
15 HttpURLConnection conection = (HttpURLConnection) urlForGetRequest.openConnection();
16 conection.setRequestMethod("GET");
17
18
19 int responseCode = conection.getResponseCode();
20
21 if (responseCode == HttpURLConnection.HTTP_OK) {
22 BufferedReader in = new BufferedReader(
23 new InputStreamReader(conection.getInputStream()));
24 StringBuffer response = new StringBuffer();
25
26 while ((readLine = in .readLine()) != null) {
27 response.append(readLine);
28 } in .close();
29
30 // print result
31 System.out.println("JSON String Result " + response.toString());
32
33
34
35 //GetAndPost.POSTRequest(response.toString());
36 } else {
37 System.out.println("GET NOT WORKED");
38 }
39
40 }
41
42
43 public static void POSTRequest() throws IOException {
44 final String POST_PARAMS= "{\n" + "\"Response status\": 101,\r \n" +
45 " \"id\": 101,\r\n" +
46 " \"title\": \"Test Title\",\r\n" +
47 " \"body\": \"Test Body\"" + "\n}";
48
49
50 /*final String POST_PARAMS = "{\n" +
51 " \"ResponseStatus\": { \n" +
52 " \"ErrorCode\": \"0\", \n" +
53 " \"Message\": \"Valid API Key\" }\n" +
54 "}";
55
56 */
57
58 //System.out.println(POST_PARAMS);
59
60 URL obj = new URL("https://api.megaventory.com/v2017a/APIkey/APIkeyGet?APIKEY=59a80b0f6999f7a5%40m103546");
61 HttpURLConnection postConnection = (HttpURLConnection) obj.openConnection();
62 postConnection.setRequestProperty("Content-Type", "application/json");
63 postConnection.setRequestMethod("POST");
64
65
66
67
68 postConnection.setDoOutput(true);
69 OutputStream os = postConnection.getOutputStream();
70 os.write(POST_PARAMS.getBytes());
71 os.flush();
72 os.close();
73 int responseCode = postConnection.getResponseCode();
74 System.out.println("POST Response Code : " + responseCode);
75 System.out.println("POST Response Message : " + postConnection.getResponseMessage());
76 //if (responseCode == HttpURLConnection.HTTP_CREATED) { //success
77 System.out.println("created");
78 BufferedReader in = new BufferedReader(new InputStreamReader(
79 postConnection.getInputStream()));
80 String inputLine;
81 StringBuffer response = new StringBuffer();
82 while ((inputLine = in .readLine()) != null) {
83 response.append(inputLine);
84 } in .close();
85 // print result
86 System.out.println(response.toString());
87 // } else {
88 // System.out.println("POST NOT WORKED");
89 //}
90 }
91
92
93
94
95 public static void main(String[] args) throws IOException {
96 //glass.MyGETRequest();
97 glass.POSTRequest();
98 }
99
100
101
102
103
104}