In this example, we will see how to use the java.net package utility to create a restful client that accesses the rest service. This is not the simplest way to create a restful client, of course, because you have to read the server-side response yourself, as well as the JSON and Java object conversions.
Request get
public class Javaneturlrestfulclient {
private static final String TargetUrl = "Http://localhost:8080/JerseyJSONExample/rest/jsonServices/print/Jamie";
public static void Main (string[] args) {
try {
URL restserviceurl = new URL (targeturl);
HttpURLConnection httpconnection = (httpurlconnection) restserviceurl.openconnection ();
Httpconnection.setrequestmethod ("GET");
Httpconnection.setrequestproperty ("Accept", "Application/json");
if (Httpconnection.getresponsecode ()! =) {
throw new RuntimeException ("HTTP GET Request Failed with Error code:"
+ httpconnection.getresponsecode ());
}
BufferedReader responsebuffer = new BufferedReader (New InputStreamReader (
(Httpconnection.getinputstream ())));
String output;
System.out.println ("Output from Server: \ n");
while (output = Responsebuffer.readline ()) = null) {
SYSTEM.OUT.PRINTLN (output);
}
Httpconnection.disconnect ();
} catch (Malformedurlexception e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
}
}
}
The results of the run-after output are:
Output from Server: {"id": 1, "FirstName": "Jamie", "Age": $, "lastName": "Diaz"}
Post submission:
public class Javaneturlrestfulclient {
private static final String TargetUrl = "Http://localhost:8080/JerseyJSONExample/rest/jsonServices/send";
public static void Main (string[] args) {
try {
URL targeturl = new URL (targeturl);
HttpURLConnection httpconnection = (httpurlconnection) targeturl.openconnection ();
Httpconnection.setdooutput (TRUE);
Httpconnection.setrequestmethod ("POST");
Httpconnection.setrequestproperty ("Content-type", "Application/json");
String input = "{\" id\ ": 1,\" firstname\ ": \" liam\ ", \" age\ ": 22,\" lastname\ ": \" marco\ "}";
OutputStream outputstream = Httpconnection.getoutputstream ();
Outputstream.write (Input.getbytes ());
Outputstream.flush ();
if (Httpconnection.getresponsecode ()! =) {
throw new RuntimeException ("Failed:http Error code:"
+ Httpconnection.getresponsecode ());
}
BufferedReader responsebuffer = new BufferedReader (new InputStreamReader (
(Httpconnection.getinputstream ()));
String output;
System.out.println ("Output from server:\n");
while (output = Responsebuffer.readline ()) = null) {
SYSTEM.OUT.PRINTLN (output);
}
Httpconnection.disconnect ();
} catch (Malformedurlexception e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
}
}
}
How to invoke a restful service in a Java client