Sending HTTP requests with Java

Posted on 08-01-2013 07:53 by graham
This tutorial describes how you can send HTTP requests, both GET and POST, and receive responses.

Sending a GET request


To send a simple GET request, we will use a HttpClient and a HttpMethod class.
HttpClient client = new HttpClient();
String requestURL = "request-url";
HttpMethod method = new GetMethod(requestURL);

int statusCode;
try
{
// execute the method
statusCode = client.executeMethod(method);
}
catch (Exception e)
{
// handle exception
...
}

// check if execution succeeded
if (statusCode != HttpStatus.SC_OK)
{
// handle error
...
}
else
{
String responseBody = method.getResponseBodyAsString();
}

Adding request parameters


Note that the request URL passed to the HttpMethod constructor is just the bare URL of the resource, without any query string parameters. Any parameters need to be added separately. There are two ways to do this. Either you can call the setQueryString method:
method.setQueryString(URIUtil.encodeQuery("param1=value1&param2=value2"))

or using HttpMethodParams:
HttpMethodParams params = new HttpMethodParams();
params.setParameter("param1", "value1");
params.setParameter("param2", "value2");
method.setParams(params);

Modifying request headers


It might happen that you want to modify or add some request headers. In the example below we add an OAuth authentication token to the request in order to authorize our request. The first parameter of the addRequestHeader method is the name of the header is Authorization, and the second one - its value.
method.addRequestHeader("Authorization", "OAuth " + token);

Sending a POST request


This doesn't differ much from sending a GET request described above. The only difference is that we are using a PostMethod class.
HttpMethod method = new PostMethod(requestURL);

Making your HTTP response look pretty


If the response body you received is a structured format, e.g. XML or JSON, you might want to have it formatted and more readable. In order to do that, all you have to do is add the "X-PrettyPrint" header to your request:
method.addRequestHeader("X-PrettyPrint", "1");
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems