Example: Java Post Json String using java.net.URL –Java Restful

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

Java Post Request Json String to a URL using java.net.URL.

Java Restful API, Java Restful Post, Java Restful URL

Example:

URL url = new URL("http://localhost:8080/healthbook/subject");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Cache-Control", "no-cache");
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
Gson gson = new Gson();
Subject subject = new Subject();
subject.setCreatedTime(new Date());
subject.setLoginID("leoncool");
subject.setTitle("test");
subject.setPrivateSet("aaaaaa");
System.out.println(gson.toJson(subject));
out.write(gson.toJson(subject));
out.close();
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
java.lang.StringBuffer sb = new java.lang.StringBuffer();
java.lang.String str = br.readLine();
while (str != null) {
sb.append(str);
str = br.readLine();
}
br.close();
java.lang.String responseString = sb.toString();
System.out.println(responseString);

Read More