GET:
ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;Importjava.net.HttpURLConnection;Importjava.net.MalformedURLException;ImportJava.net.URL; Public classgetrestclient {Private Static FinalString targeturl = "Http://localhost:8080/path/get.serv"; Public Static voidMain (string[] args) {Try{URL Restserviceurl=NewURL (TargetUrl); HttpURLConnection httpconnection=(HttpURLConnection) restserviceurl.openconnection (); Httpconnection.setrequestmethod ("GET"); Httpconnection.setrequestproperty ("Accept", "Application/json"); if(Httpconnection.getresponsecode ()! = 200) { Throw NewRuntimeException ("HTTP GET Request Failed with Error code:" +Httpconnection.getresponsecode ()); } BufferedReader Responsebuffer=NewBufferedReader (NewInputStreamReader ((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 (); } }}
POST:
ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;Importjava.net.HttpURLConnection;Importjava.net.MalformedURLException;ImportJava.net.URL; Public classpostrestclient {Private Static FinalString targeturl = "Http://localhost:8080/path/post.serv"; Public Static voidMain (string[] args) {Try{URL TargetUrl=NewURL (TargetUrl); HttpURLConnection httpconnection=(HttpURLConnection) targeturl.openconnection (); Httpconnection.setdooutput (true); Httpconnection.setrequestmethod ("POST"); Httpconnection.setrequestproperty ("Content-type", "Application/json"); String input= "{\" id\ ": 1,\" no\ ": \" no0003\ ", \" name\ ": \" Jack\ "}"; OutputStream OutputStream=Httpconnection.getoutputstream (); Outputstream.write (Input.getbytes ()); Outputstream.flush (); if(Httpconnection.getresponsecode ()! = 200) { Throw NewRuntimeException ("Failed:http error code:" +Httpconnection.getresponsecode ()); } BufferedReader Responsebuffer=NewBufferedReader (NewInputStreamReader ((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 (); } }}
Java REST Client