-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnetwork_post.java
More file actions
53 lines (35 loc) · 1.59 KB
/
network_post.java
File metadata and controls
53 lines (35 loc) · 1.59 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
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class network_post {
public static void main(String[] args) throws MalformedURLException,
IOException {
URL myUrl = new URL("https://jsonplaceholder.typicode.com/posts/");
HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
String postedString = "Hi!!! We have posted something!!! Yay!!!";
out.write(postedString.getBytes());
int responseCode = conn.getResponseCode();
System.out.print("Value of http created is: " + conn.HTTP_CREATED + "\n");
if (responseCode == conn.HTTP_CREATED) {
System.out.print("This is the response Code: " + responseCode + "\n");
System.out.print("This is the response Message from server: " + conn.
getResponseMessage() + "\n");
} else
System.out.print("GO HOME EVERYBODY :( ");
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader buffer = new BufferedReader(in);
StringBuffer fromServer = new StringBuffer();
String eachLine = null;
while ((eachLine = buffer.readLine()) != null) {
fromServer.append(eachLine);
fromServer.append(System.lineSeparator());
}
buffer.close();
System.out.print("Here is our posted content :\n" + fromServer);
System.out.println();
}
}