Apache HTTP Client Example
In this tutorial we will discuss Apache HTTP Client. Apache HttpClient makes programmatic HTTP protocol interactions easier. It is a standards based Java implementation of Http protocols, Provides complete implementation of HTTP methods (GET, POST, DELETE, PUT, HEAD, OPTIONS, TRACE). For this example I’m using Eclipse for client side Java code and PHP for writting the server side code. In this tutorial I am using HttpClient
4.5.2. In this tutorial I’ve also posted the PHP codes but would not explain them.
1. Set up the project
To start with HttpClient, download the library from https://hc.apache.org/downloads.cgi and add to your project classpath (Follow the Screenshots).
- Right click Eclipse Project -> Build Path -> Add External Archives
- Go to the directory where you’ve downloaded the HTTPClient binary. Select All and click on Open:
You are now set to use the HTTPClient in your project.
2. Different HTTPClient Classes
The main entry point of the Apache HttpClient API is the HttpClient
interface. There are different types of HttpClient
classes, useful for different scenarios. We will discuss most useful two of them.
2.1 DefaultHttpClient Class (Deprecated)
Let us start with the very basic one – DefaultHttpClient. Though it is deprecated, it will give you a simple structure to understand and start with HTTPClient. So let us start with some code, the explanation of the code is just below.
DefaultHTTPClientExmpl.java
package com.javacodegeeks.examples.rivu; import java.io.*; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; public class DefaultHTTPClientExmpl { public static void main(String[] args) { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet("http://localhost/httpclient/letsstart.php"); HttpResponse response; try { response = client.execute(request); // Get the response BufferedReader br; br = new BufferedReader(new InputStreamReader(response .getEntity().getContent())); String line = ""; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } catch (UnsupportedOperationException e) { e.printStackTrace(); } } }
And Here is the php code:
letsstart.php
<?php echo "Welcome to HTTPClient Tutorial - Java Code Geeks Examples\nWith Rivu Chakraborty"; ?>
Output
Welcome to HTTPClient Tutorial - Java Code Geeks Examples With Rivu Chakraborty
In the above code I’ve first initialized the DefaultHTTPClient
object with no parameter, then created a GET
request with new HttpGet("http://localhost/httpclient/letsstart.php")
. After that inside the try
–catch
block I’ve executed the request and got all the webpage content inside the BufferedReader
object and then used the while
loop to print all the contents.
2.2 CloseableHttpClient Class
CloseableHttpClient
is an abstract class which is the base implementation of HttpClient that also implements java.io.Closeable
. When an instance CloseableHttpClient
is no longer needed and is about to go out of scope the connection manager associated with it must be shut down by calling the CloseableHttpClient#close()
method. Here is some code to start with.
CloseableHttpClientExmpl.java
package com.javacodegeeks.examples.rivu; import java.io.*; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; public class CloseableHttpClientExmpl { public static void main(String[] args) { CloseableHttpClient client = HttpClients.createDefault(); HttpGet request = new HttpGet("http://localhost/httpclient/letsstart.php"); CloseableHttpResponse response = null; try { response = client.execute(request); int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { BufferedReader br; br = new BufferedReader(new InputStreamReader(response .getEntity().getContent())); String line = ""; while ((line = br.readLine()) != null) { System.out.println(line); } } else { System.out.println("Unexpected response status: " + status); } } catch (IOException | UnsupportedOperationException e) { e.printStackTrace(); } finally { if(null != response){ try { response.close(); client.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Output
Welcome to HTTPClient Tutorial - Java Code Geeks Examples With Rivu Chakraborty
Here I’ve used almost similar structure as the previous one for the sake of simplicity. I’ll describe the new codes and changes out here. First I’ve initialised CloseableHttpClient
with HttpClients.createDefault()
in place of HttpClient
and new DefaultHttpClient()
. Then for creating request instead of using HttpResponse
, I have used CloseableHttpResponse
and initialised it with null. After executing the request I have checked the status of the response and if it is a success (i.e. the status within the range of 200 & 300) then only I’ve continued with next steps of printing the response content. Finally I have used the finally
block to close the client
and response
objects.
3. Using ResponseHandler
ResponseHandler
is an interface that encapsulates the process of generating a response object from a HttpResponse
. At first we will try to implement simple String
ResponseHandler
. So lets go through the code below.
MyStringResponseHandler.java
package com.javacodegeeks.examples.rivu; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; class MyStringResponseHandler implements ResponseHandler<String>{ public String handleResponse(final HttpResponse response) { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); try { return null == entity ? "" : EntityUtils.toString(entity); } catch (ParseException | IOException e) { return "Error : "+e.getMessage(); } } else { return "Unexpected response status: " + status; } } }
ResponseHandlerStringExmpl.java
package com.javacodegeeks.examples.rivu; import java.io.*; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.*; import org.apache.http.util.EntityUtils; public class ResponseHandlerStringExmpl { public static void main(String[] args) { // Creates a reference to CloseableHttpClient, which is thread safe CloseableHttpClient httpclient = HttpClients.createDefault(); ResponseHandler<String> responseHandler = (ResponseHandler<String>) new MyStringResponseHandler(); try { HttpGet httpget = new HttpGet("http://localhost/httpclient/letsstart.php"); String responseBody = httpclient.execute(httpget, responseHandler); System.out.println(responseBody); } catch(IOException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Output
Welcome to HTTPClient Tutorial - Java Code Geeks Examples With Rivu Chakraborty
In the above example I have created a custom class MyStringResponseHandler
that implements the ResponseHandler<String>
so that the complete complete process of reading the contents of response in ResponseHandlerStringExmpl class
got easier. This approach is useful while parsing complex data (like JSON) from the server.
4. Parsing JSON from Server Using ResponseHandler
In this section I will demonstrate how to parse JSON from server, in a very simple approach. For this Module you need to put the JSON.simple in your CLASSPATH (with similar steps described at the start of this tutorial) before compiling and running the below codes.
MyJSONResponseHandler.java
package com.javacodegeeks.examples.rivu; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; class MyJSONResponseHandler implements ResponseHandler<JSONObject>{ public JSONObject handleResponse(final HttpResponse response) { int status = response.getStatusLine().getStatusCode(); JSONObject returnData = new JSONObject(); JSONParser parser = new JSONParser(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); try { if(null == entity){ returnData.put("status_code", "1"); returnData.put("error_message", "null Data Found"); } else { returnData = (JSONObject) parser.parse(EntityUtils.toString(entity)); } } catch (ParseException | IOException | org.json.simple.parser.ParseException e) { returnData.put("status_code", "1"); returnData.put("error_message", e.getMessage()); } } else { returnData.put("status_code", "1"); returnData.put("error_message", "Unexpected response status: " + status); } return returnData; } }
ResponseHandlerJSONExmpl.java
package com.javacodegeeks.examples.rivu; import java.io.*; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.*; import org.apache.http.util.EntityUtils; import org.json.simple.JSONObject; public class ResponseHandlerJSONExmpl { public static void main(String[] args) { // Creates a reference to CloseableHttpClient, which is thread safe CloseableHttpClient httpclient = HttpClients.createDefault(); ResponseHandler<JSONObject> responseHandler = (ResponseHandler<JSONObject>) new MyJSONResponseHandler(); try { HttpGet httpget = new HttpGet("http://localhost/httpclient/simplejsonparse.php"); JSONObject responseBody = (JSONObject) httpclient.execute(httpget, responseHandler); String statusCode = (String) responseBody.get("status_code"); if(statusCode.equalsIgnoreCase("0")){ JSONObject data = (JSONObject) responseBody.get("data"); System.out.println(data); } else { System.out.println(responseBody); } } catch(IOException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
And Here is the php code
simplejsonparse.php
<?php $data = array("status_code"=>"0", "error_message"=>"", "data"=>array("content"=>"Welcome to HTTPClient Tutorial - Java Code Geeks Examples","creator"=>"Rivu Chakraborty") ); echo json_encode($data); ?>
Output
{"content":"Welcome to HTTPClient Tutorial - Java Code Geeks Examples", "creator":"Rivu Chakraborty"}
In the above code I have followed the same approach as the previous on in using ResponseHandler
. The difference is only in parsing JSON
directly in the ResponseHandler
class. You can get more about JSON parsing and JSON writing in Java here.
5. POST Variables
So far I have discussed only with GET
requests. In this section I will discuss about POST
ing variables. Lets take a Login Example to understand it better. For the sake of simplicity I am taking user123 as hard-coded username and 123456 as hard-coded password from server side. So lets have a look at the code.
LoginExmpl.java
package com.javacodegeeks.examples.rivu; import java.io.*; import java.util.ArrayList; import java.util.List; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.*; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.simple.JSONObject; public class LoginExmpl { public static void main(String[] args) { //Take Input from User for Username and Password String uname = ""; String pass = ""; String token = ""; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { System.out.println("Enter Username"); uname = br.readLine(); System.out.println("Enter Password"); pass = br.readLine(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Creates a reference to CloseableHttpClient, which is thread safe CloseableHttpClient httpclient = HttpClients.createDefault(); ResponseHandler responseHandler = (ResponseHandler) new MyJSONResponseHandler(); try { HttpPost httpost = new HttpPost("http://localhost/httpclient/loginexample.php"); List params = new ArrayList(); params.add(new BasicNameValuePair("username", uname)); params.add(new BasicNameValuePair("password", pass)); httpost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8)); JSONObject responseBody = (JSONObject) httpclient.execute(httpost, responseHandler); String statusCode = (String) responseBody.get("status_code"); if(statusCode.equalsIgnoreCase("0")){ JSONObject data = (JSONObject) responseBody.get("data"); token = (String) data.get("token"); // Keep Token for future refferences } System.out.println(responseBody.get("error_message")); } catch(IOException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
And Here is the php code:
loginexample.php
<?php $userName = "user123";//HardCoded Username $pass = "123456"; //HardCoded Password $post_username = ""; if(isset($_POST['username'])){ $post_username = $_POST['username']; } $post_password = ""; if(isset($_POST['password'])){ $post_password = $_POST['password']; } if(($userName == $post_username)&&($pass == $post_password)){ $status_code = "0"; $error_message = "Login Successfull"; $token = "abcd1234"; } else { $status_code = "1"; $error_message = "Invalid Username or Password"; $token = ""; } $data = array("status_code"=>$status_code, "error_message"=>$error_message, "data"=>array("token"=>$token) ); echo json_encode($data); ?>
Output
Enter Username user123 Enter Password 123456 Login Successfull Enter Username bjk Enter Password fwdsv Invalid Username or Password
In the above code I have used HttpPost
instead of HttpGet
. As we know that Post
requests generally requires parameters to post. We have used org.apache.http.NameValuePair
for that purpose. We took username and password as user input then aded it to the NameValuePair
. Basically org.apache.http.NameValuePair
is an interface
, so we used org.apache.http.message.BasicNameValuePair;
to initialise it. To set the parameters to the post request in UTF-8 format we used httpost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
. The remaining stays same, except that instead of printing the data, we’ve printed the error_message and kept token for future use (This will be usefull when you are working on a real-time project).
6. Download the source code
So this was an example on Apache HTTP Client
You can download the full source code of this example here: Apache HTTPClient Example