Making HTTP requests with Java

NotNullProduction
Aug 25, 2017 · 4 min read

Painless way to make HTTP requests with Java.

In this article, I will show you how to make HTTP requests in Java using HTTPClient library, this is probably the easiest HTTP client to use, I know because I wrote it, and I have strong aversion towards difficult things ;-). You can download the library here.

To start, create an HTTPClient object. HTTPClient implements AutoCloseable so you should create it inside try with resource block

try (HTTPClient client = new HTTPClient("http://httpbin.org"))
{
// some code here
}
catch (IOException | ClientException ex)
{
/* handle exception */
}

Now let’s make a simple HTTP GET request, the path is ‘/ip’

try (HTTPClient client = new HTTPClient("http://httpbin.org"))
{
/* Create a GET request, the requested path is "/ip"
(leading / is required) */
client.createRequest(HTTPMethods.GET, "/ip");
/* Send the request. */
client.sendRequest();
/* Read content body into an output stream */
ByteArrayOutputStream bos = new ByteArrayOutputStream();
client.readContent(bos);
System.out.println(bos.toString());
}
catch (IOException | ClientException ex)
{
/* handle exception */
}

First create a request using createRequest method, then send the request using sendRequest. After sendRequest returns, you may read response header returned by the server, this is optional. Finally call readContent method to read the response into an output stream(ByteArrayOutputStream is used in the example — but any output stream can be used. For example you can use FileOutputStream to write the response into a file).

To add headers, call setRequestOption, pass field name and value; for example client.setRequestOption(“Accept”, “*/*”).

To send a request along with query string create a HashMap<String, String>, fill it with required values, then pass it to createRequest method along with the path.

try (HTTPClient client = new HTTPClient("http://httpbin.org"))
{
HashMap qParam = new HashMap<>();
qParam.put("item_1", "value");
qParam.put("item_2", "value");
qParam.put("item_3", "value");
/* Create a GET request, the requested path is "/ip"
(leading / is required) */
client.createRequest(HTTPMethods.GET, "/get", qParam);
client.setRequestOption("Accept", "*/*").
/* Send the request. */
client.sendRequest();
/* Read content body into an output stream
(you can use any output stream)*/
ByteArrayOutputStream bos = new ByteArrayOutputStream();
client.readContent(bos);
System.out.println(bos.toString());
}
catch (IOException | ClientException ex)
{
/* handle exception */
}

To make requests that include content body (POST, PUT request etc.) you need to pass an input stream and the length of data (in bytes) to sendRequest method, any type of input stream can be used. Here’s an example

try (HTTPClient client = new HTTPClient("http://httpbin.org"))
{
/* Send 'form' data, the application/x-www-form-urlencoded
type */

/* Create the content */
HashMap qParam = new HashMap<>();
qParam.put("item_1", "value");
qParam.put("item_2", "value");
qParam.put("item_3", "value");
String formData = HTTPUtils.buildQueryString(qParam, true);
/* Put it in an input stream */
byte[] formDataInBytes = formData.getBytes();
ByteArrayInputStream ins;
ins = new ByteArrayInputStream(formDataInBytes);

/* Create request */
client.createRequest(HTTPMethods.POST, "/post");
client.setRequestOption(Headers.CONTENT_TYPE,
"application/x-www-form-urlencoded");

/* Send the request.
Pass input stream and the length of the data */
client.sendRequest(ins, formDataInBytes.length);

/* Read content body into an output stream
(you can use any output stream)*/
ByteArrayOutputStream bos = new ByteArrayOutputStream();
client.readContent(bos);
System.out.println(bos.toString());
}
catch (IOException | ClientException ex)
{
/* handle exception */
}

Sending multipart message

To send multipart message (multipart/* content type), use MutiPartInputStream. First you need to wrap the each “message” that you want to send inside MultiPartMessage class (the message can be a file, or raw bytes). Then pass all of them to MutiPartInputStream constructor.

try (HTTPClient client = new HTTPClient("http://httpbin.org"))
{
/* Multipart message, raw bytes + null header */
MultiPartMessage msg1;
msg1 = new MultiPartMessage("Some text".getBytes(), null);
/* Multipart message, file + null header */
MultiPartMessage msg2;
msg2 = new MultiPartMessage(new File("name"), null);
/* Multipart message, raw bytes + null header */
MultiPartMessage msg3;
msg3 = new MultiPartMessage("More text".getBytes(), null);
/* Create MultiPartInputStream, and pass the messages */
MultiPartInputStream ins;
ins = new MultiPartInputStream(msg1, msg2, msg3);

/* Create request, then set Content-Type header */
client.createRequest(HTTPMethods.POST, "/post");
client.setRequestOption(Headers.CONTENT_TYPE,
"multipart/related");
/* Send the request. */
client.sendRequest(ins, ins.length());

/* Read content body into an output stream
(you can use any output stream)*/
ByteArrayOutputStream bos = new ByteArrayOutputStream();
client.readContent(bos);
System.out.println(bos.toString());
}
catch (IOException | ClientException ex)
{
/* handle exception */
}

Cancellable transfer

Upload and download can be cancelled — this is useful when downloading, or uploading a lot of data. To enable this, create a subclass of ProgressMonitor, and implement the onProgress method. onProgress is called by HTTPClient periodically while uploading or downloading; to cancel make onProgress return true.

try (HTTPClient client = new HTTPClient("http://httpbin.org"))
{
/* Create a GET request, the requested path is "/ip"
(leading / is required) */
client.createRequest(HTTPMethods.GET, "/ip");
/* Send the request. */
client.sendRequest();

/* Read content body into an output stream
(you can use any output stream)*/
ByteArrayOutputStream bos = new ByteArrayOutputStream();
client.readContent(bos,
new ProgressMonitor(Operation.DOWNLOAD)
{
@Override
public boolean onProgress(long done, long total)
{
/* change this to true to quit*/
boolean cancel = false;
return cancel;
}
});
System.out.println(bos.toString());
}
catch (IOException | ClientException ex)
{
/* handle exception */
}

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade