This article introduces a utility class that makes a connection to a HTTP server by sending a GET/POST request and receiving response from the server. The HttpUtility class is built upon the HttpURLConnection class under java.net package, and has two methods for sending a request to a remote server:

    •  sendGetRequest(requestURL): accepts only the URL string.
    •  sendPostRequest(requestURL, params): accepts a URL string and a HashMap containing POST parameters.

Both methods return an HttpURLConnection object which has been made with the remote server. So we can use this object to invoke methods of the HttpURLConnection class when needed, such as checking HTTP status code, or HTTP response message.

The class also provides two methods for reading the server's response:

    •  readSingleLineRespone(): returns a String.
    •  readMultipleLinesRespone(): returns an array of Strings.

As the names suggest, the first method is suitable if the server returns a simple response such as a String; and the second one is suitable if the server returns something bigger.

Finally, there is a method to close the connection with the server:

    • disconnect()

Here is the source code of this utility class:

package net.codejava.networking;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * This class encapsulates methods for requesting a server via HTTP GET/POST and
 * provides methods for parsing response from the server.
 * 
 * @author www.codejava.net
 * 
 */
public class HttpUtility {

	/**
	 * Represents an HTTP connection
	 */
	private static HttpURLConnection httpConn;

	/**
	 * Makes an HTTP request using GET method to the specified URL.
	 * 
	 * @param requestURL
	 *            the URL of the remote server
	 * @return An HttpURLConnection object
	 * @throws IOException
	 *             thrown if any I/O error occurred
	 */
	public static HttpURLConnection sendGetRequest(String requestURL)
			throws IOException {
		URL url = new URL(requestURL);
		httpConn = (HttpURLConnection) url.openConnection();
		httpConn.setUseCaches(false);

		httpConn.setDoInput(true); // true if we want to read server's response
		httpConn.setDoOutput(false); // false indicates this is a GET request

		return httpConn;
	}

	/**
	 * Makes an HTTP request using POST method to the specified URL.
	 * 
	 * @param requestURL
	 *            the URL of the remote server
	 * @param params
	 *            A map containing POST data in form of key-value pairs
	 * @return An HttpURLConnection object
	 * @throws IOException
	 *             thrown if any I/O error occurred
	 */
	public static HttpURLConnection sendPostRequest(String requestURL,
			Map<String, String> params) throws IOException {
		URL url = new URL(requestURL);
		httpConn = (HttpURLConnection) url.openConnection();
		httpConn.setUseCaches(false);

		httpConn.setDoInput(true); // true indicates the server returns response

		StringBuffer requestParams = new StringBuffer();

		if (params != null && params.size() > 0) {

			httpConn.setDoOutput(true); // true indicates POST request

			// creates the params string, encode them using URLEncoder
			Iterator<String> paramIterator = params.keySet().iterator();
			while (paramIterator.hasNext()) {
				String key = paramIterator.next();
				String value = params.get(key);
				requestParams.append(URLEncoder.encode(key, "UTF-8"));
				requestParams.append("=").append(
						URLEncoder.encode(value, "UTF-8"));
				requestParams.append("&");
			}

			// sends POST data
			OutputStreamWriter writer = new OutputStreamWriter(
					httpConn.getOutputStream());
			writer.write(requestParams.toString());
			writer.flush();
		}

		return httpConn;
	}

	/**
	 * Returns only one line from the server's response. This method should be
	 * used if the server returns only a single line of String.
	 * 
	 * @return a String of the server's response
	 * @throws IOException
	 *             thrown if any I/O error occurred
	 */
	public static String readSingleLineRespone() throws IOException {
		InputStream inputStream = null;
		if (httpConn != null) {
			inputStream = httpConn.getInputStream();
		} else {
			throw new IOException("Connection is not established.");
		}
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				inputStream));

		String response = reader.readLine();
		reader.close();

		return response;
	}

	/**
	 * Returns an array of lines from the server's response. This method should
	 * be used if the server returns multiple lines of String.
	 * 
	 * @return an array of Strings of the server's response
	 * @throws IOException
	 *             thrown if any I/O error occurred
	 */
	public static String[] readMultipleLinesRespone() throws IOException {
		InputStream inputStream = null;
		if (httpConn != null) {
			inputStream = httpConn.getInputStream();
		} else {
			throw new IOException("Connection is not established.");
		}

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				inputStream));
		List<String> response = new ArrayList<String>();

		String line = "";
		while ((line = reader.readLine()) != null) {
			response.add(line);
		}
		reader.close();

		return (String[]) response.toArray(new String[0]);
	}
	
	/**
	 * Closes the connection if opened
	 */
	public static void disconnect() {
		if (httpConn != null) {
			httpConn.disconnect();
		}
	}
}

 

 

The following test program demonstrates how to use the utility class:

package net.codejava.networking;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class HttpUtilityTester {

	/**
	 * This program uses the HttpUtility class to send a GET request to
	 * Google home page; and send a POST request to Gmail login page.
	 */
	public static void main(String[] args) {
		// test sending GET request
		String requestURL = "http://www.google.com";
		try {
			HttpUtility.sendGetRequest(requestURL);
			String[] response = HttpUtility.readMultipleLinesRespone();
			for (String line : response) {
				System.out.println(line);
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		HttpUtility.disconnect();
		
		
		System.out.println("=====================================");
		
		// test sending POST request
		Map<String, String> params = new HashMap<String, String>();
		requestURL = "https://accounts.google.com/ServiceLoginAuth";
		params.put("Email", "your_email");
		params.put("Passwd", "your_password");
		
		try {
			HttpUtility.sendPostRequest(requestURL, params);
			String[] response = HttpUtility.readMultipleLinesRespone();
			for (String line : response) {
				System.out.println(line);
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		HttpUtility.disconnect();
	}
}

 

Recommended Book: Fundamental Networking in Java

Recommended Book: Java Network Programming, Third Edition

Attachments:
Download this file (HttpUtility.java)HttpUtility.java[Java source code]4 kB
avatar
Could you assist me please in making use of this code.
I am making use of the code in wavemaker (wavemaker.com) and so far I am struggling in that within java, the returned result of the HTTP GET only displays some of the the lines but when I try to count number of items in the "line", there is shown some data does exist.
Since this comment utility does not allow attachment, please use my e-mail and I will forward you some screendumps and an xcel file showing what I am getting

Kind Regards,
Kotin Karwak
VOTES:0
avatar
I have put more details on this link on wavemaker forum.

dev.wavemaker.com/forums/?q=node/10219
VOTES:0
avatar
Hi kotin karwak,

I have looked at the link you posted. I think there is a problem with this line:

if(line == " ") {...

The bottom line is, don't use the == operator to compare String literals. Instead, you should use this form:

if (line.equals(" ")) {...

Hope this helps.
VOTES:0
avatar
you sir are an angel'
VOTES:0
avatar
Thankyou for sharing this! I finally got my code working! I tried to do the very same thing using my own code (almost 90% the same, except for that I was using an OutputStream instead of an OutputStreamWriter) and had not success. Thanks!
VOTES:0
avatar
hi Kevin,
Glad to see it helps. Yeah, the OutputStreamWriter won't work because the POST data is sent as text.
VOTES:0
avatar
Im using your [color=aqua][/color]class on a project so, i have to send a Image on the request... could you tell me how to do it?
VOTES:0
avatar
bonsoir, j'ai crée un service web et j'ai importer ce service dans wavemaker je peut l'afficher dans la fenetre de wavemaker mais mon probléme c'est comment je peut modifier dans le service exemple ajouter ou supprimer et merci
VOTES:0
avatar
quickynator wrote:
Im using your [color=aqua][/color]class on a project so, i have to send a Image on the request... could you tell me how to do it?
Here's the relevant tutorial you need: Upload files by sending multipart request programmatically
VOTES:0
Start learning on Udemy today!