JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Java client for restful web service using java.net package


In this page you will come to know how to create java client for restful web services using java.net package. We will have two sections here, the first section talks about how to connect to "GET" request, and the second section shows how to connect to "POST" type of requests.

We are referring to the previous example as a restful web services.

Java Client for GET Request

package com.java2novice.rest.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class RestJavaNetClient {

	public static void main(String a[]){
		
		String url = "http://localhost:8080/RestfulWebServices/order-inventory/order/1016";
		HttpURLConnection urlConn = null;
		BufferedReader reader = null;
		try {
			URL urlObj = new URL(url);
			urlConn = (HttpURLConnection) urlObj.openConnection();
			urlConn.setRequestMethod("GET");
			urlConn.setConnectTimeout(5000);
			urlConn.setReadTimeout(5000);
			urlConn.setRequestProperty("Accept", "application/json");
			if (urlConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				System.err.println("Unable to connect to the URL...");
				return;
			}
			System.out.println("Connected to the server...");
			InputStream is = urlConn.getInputStream();
			reader = new BufferedReader(new InputStreamReader((is)));
			System.out.println("Reading data from server...");
			String tmpStr = null;
			while((tmpStr = reader.readLine()) != null){
				System.out.println(tmpStr);
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if(reader != null) reader.close();
				if(urlConn != null) urlConn.disconnect();
			} catch(Exception ex){
				
			}
		}
	}
}

The output for above code is:

Output:
Connected to the server...
Reading data from server...
{"custmer":"Java2Novice","address":"Bangalore","bill-amount":"$2000"}

Java Client for POST Request

In this example you will see how to send json input through java client using POST method:

package com.java2novice.rest.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class PostJavaNetClient {

	public static void main(String a[]){
		
		String url = "http://localhost:8080/RestfulWebServices/order-inventory/order";
		HttpURLConnection urlConn = null;
		BufferedReader reader = null;
		OutputStream ouputStream = null;
		String jsonInput = "{\"custmer\":\"Java2novice\",\"address\":\"Bangalore\","+
							"\"bill-amount\":\"$2000\"}";
		try {
			URL urlObj = new URL(url);
			urlConn = (HttpURLConnection) urlObj.openConnection();
			urlConn.setDoOutput(true);
			urlConn.setRequestMethod("POST");
			urlConn.setRequestProperty("Content-Type", "application/json");
			urlConn.setConnectTimeout(5000);
			urlConn.setReadTimeout(5000);
			urlConn.setRequestProperty("Accept", "application/json");
			// send json input request
			ouputStream = urlConn.getOutputStream();
			ouputStream.write(jsonInput.getBytes());
			ouputStream.flush();
			if (urlConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				System.err.println("Unable to connect to the URL...");
				return;
			}
			System.out.println("Connected to the server...");
			InputStream is = urlConn.getInputStream();
			reader = new BufferedReader(new InputStreamReader((is)));
			String tmpStr = null;
			while((tmpStr = reader.readLine()) != null){
				System.out.println(tmpStr);
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if(reader != null) reader.close();
				if(urlConn != null) urlConn.disconnect();
			} catch(Exception ex){
				
			}
		}
	}
}

The output for above code is:

Output:
Connected to the server...
Your order is in-progress
<< Previous Program | Next Program >>

Restful Web Services Examples

  1. Restful web services using RESTEasy hello world example.
  2. Restful web services using Jersey hello world example.
  3. JAX-RS @Path annotation example
  4. JAX-RS @Path annotation with regular expression match example
  5. JAX-RS @PathParam annotation example
  6. JAX-RS @QueryParam and @DefaultValue annotations example
  7. JAX-RS @MatrixParam annotation example
  8. How to read multiple values of a query paramter in JAX-RS restful web services?
  9. How to pass header parameters as method inputs in JAX-RS restful web services?
  10. How to read header parameters in JAX-RS restful web services?
  11. JAX-RS @FormParam annotation example
  12. How to upload file using Jersey restful web services?
  13. How to download file using java restful web services?
  14. XML based Restful web service with RESTEasy and JAXB.
  15. XML based Restful web service with Jersey and JAXB.
  16. Json based Restful web service with RESTEasy, Jettison and JAXB
  17. Json based Restful web service with RESTEasy and Jackson
  18. Json based Restful web service with Jersey and Jackson
  19. How to input json request with Jersey and Jackson?
  20. Java client for restful web service using java.net package
  21. Java client for restful web service using Jersey API
  22. Java restful webservices with HTTP basic authentication.
Knowledge Centre
Procedural Vs Object-oriented Programs
In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code.

In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code.
Famous Quotations
Be yourself; everyone else is already taken.
-- Oscar Wilde

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.