Here we will use “java.net.URL” and “java.net.HttpURLConnection” to create a simple Java client to send “GET” and “POST” request.
Output:
NOTE: Same way, by using "POST" method we can create Java Client using java.net.URL with few changes in the above code.
GET Request
REST service that return “json” data back to client.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Path("/json/product") | |
public class JSONService { | |
@GET | |
@Path("/get") | |
@Produces("application/json") | |
public Product getProductInJSON() { | |
Product product = new Product(); | |
product.setName("iPad 3"); | |
product.setQty(999); | |
return product; | |
} | |
//... |
Java client to send a “GET” request:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.net.HttpURLConnection; | |
import java.net.MalformedURLException; | |
import java.net.URL; | |
public class NetClientGet { | |
// http://localhost:8080/RESTfulExample/json/product/get | |
public static void main(String[] args) { | |
try { | |
URL url = new URL("http://localhost:8080/RESTfulExample/json/product/get"); | |
HttpURLConnection conn = (HttpURLConnection)url.openConnection(); | |
conn.setRequestMethod("GET"); | |
conn.setRequestProperty("Accept", "application/json"); | |
if (conn.getResponseCode() != 200) { | |
throw new RuntimeException("Failed : HTTP error code : " | |
+ conn.getResponseCode()); | |
} | |
BufferedReader br = new BufferedReader(new InputStreamReader( | |
(conn.getInputStream()))); | |
String output; | |
System.out.println("Output from Server .... \n"); | |
while ((output = br.readLine()) != null) { | |
System.out.println(output); | |
} | |
conn.disconnect(); | |
} | |
catch (MalformedURLException e) { | |
e.printStackTrace(); | |
} | |
catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Output from Server .... {"qty":999,"name":"iPad 3"}
NOTE: Same way, by using "POST" method we can create Java Client using java.net.URL with few changes in the above code.