
This java based tutorial is designed to provide a basic overview of how to use HttpClient.
Downloaded HttpClient and dependencies listed below that are required to put them on your classpath.
- httpclient-4.2.3.jar from http://hc.apache.org/downloads.cgi/li>
- commons-codec.jar from http://commons.apache.org/codec/
- commons-logging.jar from http://commons.apache.org/logging/
- junit.jar from http://www.junit.org/
The general process for using HttpClient consists of a number of steps:
- Create an instance of HttpClient.
- Create an instance of one of the methods (GetMethod in this case). The URL to connect to is passed in to the the method constructor.
- Tell HttpClient to execute the method.
- Read the response.
- Release the connection.
- Deal with the response.
package com.jkoder.http;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient client = new HttpClient();
GetMethod method = new GetMethod("jkoder.com");
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
//If status code is not 200.
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
System.out.println(new String(responseBody));
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
}
}
Jkoder.com Tutorials, Tips and interview questions for Java, J2EE, Android, Spring, Hibernate, Javascript and other languages for software developers