Useful Resources

Apache HttpClient – Useful Resources ”; Previous Next The following resources contain additional information on Apache HttpClient. Please use them to get more in-depth knowledge on this topic. Useful Links on Apache HttpClient Apache HttpClient − Official Website of Apache HttpClient. Apache HttpClient Wiki − Wikipedia Reference for Apache HttpClient. To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

Http Get Request

Apache HttpClient – Http Get Request ”; Previous Next The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data. The HttpClient API provides a class named HttpGet which represents the get request method. Follow the steps given below to send a get request using HttpClient library Step 1 – Create a HttpClient object The createDefault() method of the HttpClients class returns a CloseableHttpClient object, which is the base implementation of the HttpClient interface. Using this method, create an HttpClient object as shown below − CloseableHttpClient httpclient = HttpClients.createDefault(); Step 2 – Create an HttpGet Object The HttpGet class represents the HTTPGET request which retrieves the information of the given server using a URI. Create a HTTP GET request by instantiating this class. The constructor of this class accepts a String value representing the URI. HttpGet httpget = new HttpGet(“https://www.tutorialspoint.com/”); Step 3 – Execute the Get Request The execute() method of the CloseableHttpClient class accepts a HttpUriRequest (interface) object (i.e. HttpGet, HttpPost, HttpPut, HttpHead etc.) and returns a response object. Execute the request using this method as shown below − HttpResponse httpresponse = httpclient.execute(httpget); Example Following is an example which demonstrates the execution of the HTTP GET request using HttpClient library. import java.util.Scanner; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class HttpGetExample { public static void main(String args[]) throws Exception{ //Creating a HttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); //Creating a HttpGet object HttpGet httpget = new HttpGet(“https://www.tutorialspoint.com/ “); //Printing the method used System.out.println(“Request Type: “+httpget.getMethod()); //Executing the Get request HttpResponse httpresponse = httpclient.execute(httpget); Scanner sc = new Scanner(httpresponse.getEntity().getContent()); //Printing the status line System.out.println(httpresponse.getStatusLine()); while(sc.hasNext()) { System.out.println(sc.nextLine()); } } } Output The above program generates the following output − Request Type: GET <!DOCTYPE html> <!–[if IE 8]><html class = “ie ie8”> <![endif]–> <!–[if IE 9]><html class = “ie ie9”> <![endif]–> <!–[if gt IE 9]><!–> <html lang = “en-US”> <!–<![endif]–> <head> <!– Basic –> <meta charset = “utf-8”> <title>Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Apache Commons Collections</title> <meta name = “Description” content = “Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Intellij Idea, Apache Commons Collections, Java 9, GSON, TestLink, Inter Process Communication (IPC), Logo, PySpark, Google Tag Manager, Free IFSC Code, SAP Workflow”/> <meta name = “Keywords” content = “Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Gson, TestLink, Inter Process Communication (IPC), Logo”/> <meta http-equiv = “X-UA-Compatible” content = “IE = edge”> <meta name = “viewport” content = “width = device-width,initial-scale = 1.0,userscalable = yes”> <link href = “https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css” rel = “stylesheet” type = “text/css” /> <link rel = “stylesheet” href=”/questions/css/home.css?v = 3″ /> <script src = “/questions/js/jquery.min.js”></script> <script src = “/questions/js/fontawesome.js”></script> <script src = “https://cdn.muicss.com/mui-0.9.39/js/mui.min.js”></script> </head> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . </script> </body> </html> Print Page Previous Next Advertisements ”;

Discussion

Discuss Apache HttpClient ”; Previous Next Http client is a transfer library. It resides on the client side, sends and receives Http messages. It provides up to date, feature-rich, and an efficient implementation which meets the recent Http standards. Print Page Previous Next Advertisements ”;

Closing Connection

Apache HttpClient – Closing Connection ”; Previous Next If you are processing HTTP responses manually instead of using a response handler, you need to close all the http connections by yourself. This chapter explains how to close the connections manually. While closing HTTP connections manually follow the steps given below − Step 1 – Create an HttpClient object The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface. Using this method, create an HttpClient object as shown below − CloseableHttpClient httpClient = HttpClients.createDefault(); Step 2 – Start a try-finally block Start a try-finally block, write the remaining code in the programs in the try block and close the CloseableHttpClient object in the finally block. CloseableHttpClient httpClient = HttpClients.createDefault(); try{ //Remaining code . . . . . . . . . . . . . . . }finally{ httpClient.close(); } Step 3 – Create a HttpGetobject The HttpGet class represents the HTTP GET request which retrieves the information of the given server using a URI. Create a HTTP GET request by instantiating the HttpGet class by passing a string representing the URI. HttpGet httpGet = new HttpGet(“https://www.tutorialspoint.com/”); Step 4 – Execute the Get request The execute() method of the CloseableHttpClient object accepts a HttpUriRequest (interface) object (i.e. HttpGet, HttpPost, HttpPut, HttpHead etc.) and returns a response object. Execute the request using the given method − HttpResponse httpResponse = httpclient.execute(httpGet); Step 5 – Start another (nested) try-finally Start another try-finally block (nested within the previous try-finally), write the remaining code in the programs in this try block and close the HttpResponse object in the finally block. CloseableHttpClient httpclient = HttpClients.createDefault(); try{ . . . . . . . . . . . . . . CloseableHttpResponse httpresponse = httpclient.execute(httpget); try{ . . . . . . . . . . . . . . }finally{ httpresponse.close(); } }finally{ httpclient.close(); } Example Whenever you create/obtain objects such as request, response stream, etc., start a try finally block in the next line, write the remaining code within the try and close the respective object in the finally block as demonstrated in the following program − import java.util.Scanner; 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.HttpClients; public class CloseConnectionExample { public static void main(String args[])throws Exception{ //Create an HttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); try{ //Create an HttpGet object HttpGet httpget = new HttpGet(“https://www.tutorialspoint.com/”); //Execute the Get request CloseableHttpResponse httpresponse = httpclient.execute(httpget); try{ Scanner sc = new Scanner(httpresponse.getEntity().getContent()); while(sc.hasNext()) { System.out.println(sc.nextLine()); } }finally{ httpresponse.close(); } }finally{ httpclient.close(); } } } Output On executing the above program, the following output is generated − <!DOCTYPE html> <!–[if IE 8]><html class = “ie ie8”> <![endif]–> <!–[if IE 9]><html class = “ie ie9”> <![endif]–> <!–[if gt IE 9]><!–> <html lang = “en-US”> <!–<![endif]–> <head> <!– Basic –> <meta charset = “utf-8”> <meta http-equiv = “X-UA-Compatible” content = “IE = edge”> <meta name = “viewport” content = “width = device-width,initial-scale = 1.0,userscalable = yes”> <link href = “https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css” rel = “stylesheet” type = “text/css” /> <link rel = “stylesheet” href = “/questions/css/home.css?v = 3” /> <script src = “/questions/js/jquery.min.js”></script> <script src = “/questions/js/fontawesome.js”></script> <script src = “https://cdn.muicss.com/mui-0.9.39/js/mui.min.js”></script> </head> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . <script> window.dataLayer = window.dataLayer || []; function gtag() {dataLayer.push(arguments);} gtag(”js”, new Date()); gtag(”config”, ”UA-232293-17”); </script> </body> </html> Print Page Previous Next Advertisements ”;

Quick Guide

Apache HttpClient – Quick Guide ”; Previous Next Apache HttpClient – Overview The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative, hypermedia information systems. This is the foundation for data communication for the World Wide Web (i.e., Internet) since 1990. HTTP is a generic and stateless protocol which can be used for other purposes as well using extensions of its request methods, error codes, and headers. Basically, HTTP is a TCP/IP based communication protocol, that is used to deliver data (HTML files, image files, query results, etc.) on the World Wide Web. The default port is TCP 80, but other ports can be used as well. It provides a standardized way for computers to communicate with each other. HTTP specification defines how clients” request data will be constructed and sent to the server, and how the servers respond to these requests. What is Http Client Http client is a transfer library, it resides on the client side, sends and receives HTTP messages. It provides up to date, feature-rich and, efficient implementation which meets the recent HTTP standards. In addition to this using client library, one can build HTTP based applications such as web browsers, web service clients, etc. Features of Http Client Following are the prominent features of Http client − HttpClient library implements all the available HTTP methods. HttpClient library provides APIs to secure the requests using the Secure Socket Layer protocol. Using HttpClient, you can establish connections using proxies. You can authenticate connections using authentication schemes such as Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session etc. HttpClient library supports sending requests through multiple threads. It manages multiple connections established from various threads using ClientConnectionPoolManager. Using Apache HttpClient library, you can set connection timeouts. Apache HttpClient – Environment Setup In this chapter, we will explain how to set an environment for HttpClient in Eclipse IDE. Before proceeding with the installation, make sure that you already have Eclipse installed in your system. If not, download and install Eclipse. For more information on Eclipse, please refer to our Eclipse Tutorial. Step 1 – Download the dependency JAR file Open the official homepage of the HttpClient (components) website and go to the download page Then, download the latest stable version of HttpClient. Here, throughout the tutorial, we are using the version 4.5.6 hence download the file 4.5.6.zip. Within the downloaded folder, you will find a folder named lib and this contains the required Jar files that are to be added in the classpath of your project, to work with HttpClient. Step 2 – Create a project and set build path Open eclipse and create a sample project. Right click on the project select the option Build Path → Configure Build Path as shown below. In the Java Build Path frame in the Libraries tab, click on Add External JARs. And select all the jar files in the lib folder and, click on Apply and Close. You are all set to work with HttpClient library in eclipse. Apache HttpClient – Http Get Request The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data. The HttpClient API provides a class named HttpGet which represents the get request method. Follow the steps given below to send a get request using HttpClient library Step 1 – Create a HttpClient object The createDefault() method of the HttpClients class returns a CloseableHttpClient object, which is the base implementation of the HttpClient interface. Using this method, create an HttpClient object as shown below − CloseableHttpClient httpclient = HttpClients.createDefault(); Step 2 – Create an HttpGet Object The HttpGet class represents the HTTPGET request which retrieves the information of the given server using a URI. Create a HTTP GET request by instantiating this class. The constructor of this class accepts a String value representing the URI. HttpGet httpget = new HttpGet(“https://www.tutorialspoint.com/”); Step 3 – Execute the Get Request The execute() method of the CloseableHttpClient class accepts a HttpUriRequest (interface) object (i.e. HttpGet, HttpPost, HttpPut, HttpHead etc.) and returns a response object. Execute the request using this method as shown below − HttpResponse httpresponse = httpclient.execute(httpget); Example Following is an example which demonstrates the execution of the HTTP GET request using HttpClient library. import java.util.Scanner; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class HttpGetExample { public static void main(String args[]) throws Exception{ //Creating a HttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); //Creating a HttpGet object HttpGet httpget = new HttpGet(“https://www.tutorialspoint.com/ “); //Printing the method used System.out.println(“Request Type: “+httpget.getMethod()); //Executing the Get request HttpResponse httpresponse = httpclient.execute(httpget); Scanner sc = new Scanner(httpresponse.getEntity().getContent()); //Printing the status line System.out.println(httpresponse.getStatusLine()); while(sc.hasNext()) { System.out.println(sc.nextLine()); } } } Output The above program generates the following output − Request Type: GET <!DOCTYPE html> <!–[if IE 8]><html class = “ie ie8”> <![endif]–> <!–[if IE 9]><html class = “ie ie9”> <![endif]–> <!–[if gt IE 9]><!–> <html lang = “en-US”> <!–<![endif]–> <head> <!– Basic –> <meta charset = “utf-8”> <title>Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Apache Commons Collections</title> <meta name = “Description” content = “Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Intellij Idea, Apache Commons Collections, Java 9, GSON, TestLink, Inter Process Communication (IPC), Logo, PySpark, Google Tag Manager, Free IFSC Code, SAP Workflow”/> <meta name = “Keywords” content = “Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Gson, TestLink, Inter Process Communication (IPC), Logo”/> <meta http-equiv = “X-UA-Compatible” content = “IE = edge”> <meta name = “viewport” content = “width = device-width,initial-scale = 1.0,userscalable = yes”> <link href = “https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css” rel = “stylesheet” type = “text/css” /> <link rel = “stylesheet” href=”/questions/css/home.css?v = 3″ /> <script src = “/questions/js/jquery.min.js”></script> <script src = “/questions/js/fontawesome.js”></script> <script src = “https://cdn.muicss.com/mui-0.9.39/js/mui.min.js”></script> </head> . . . . . . .

Using Proxy

Apache HttpClient – Using Proxy ”; Previous Next A Proxy server is an intermediary server between the client and the internet. Proxy servers offer the following basic functionalities − Firewall and network data filtering Network connection sharing Data caching Using HttpClient library, you can send a HTTP request using a proxy. Follow the steps given below − Step 1 – Create a HttpHost object Instantiate the HttpHost class of the org.apache.http package by passing a string parameter representing the name of the proxy host, (from which you need the requests to be sent) to its constructor. //Creating an HttpHost object for proxy HttpHost proxyHost = new HttpHost(“localhost”); In the same way, create another HttpHost object to represent the target host to which requests need to be sent. //Creating an HttpHost object for target HttpHost targetHost = new HttpHost(“google.com”); Step 2 – Create an HttpRoutePlanner object The HttpRoutePlanner interface computes a route to a specified host. Create an object of this interface by instantiating the DefaultProxyRoutePlanner class, an implementation of this interface. As a parameter to its constructor, pass the above created proxy host − //creating a RoutePlanner object HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyhost); Step 3 – Set the route planner to a client builder Using the custom() method of the HttpClients class, create a HttpClientBuilder object and, to this object set the route planner created above, using the setRoutePlanner() method. //Setting the route planner to the HttpClientBuilder object HttpClientBuilder clientBuilder = HttpClients.custom(); clientBuilder = clientBuilder.setRoutePlanner(routePlanner); Step 4 – Build the CloseableHttpClient object Build the CloseableHttpClient object by calling the build() method. //Building a CloseableHttpClient CloseableHttpClient httpClient = clientBuilder.build(); Step 5 – Create a HttpGetobject Create a HTTP GET request by instantiating the HttpGet class. //Creating an HttpGet object HttpGet httpGet = new HttpGet(“/”); Step 6 – Execute the request One of the variants of the execute() method accepts an HttpHost and HttpRequest objects and executes the request. Execute the request using this method − //Executing the Get request HttpResponse httpResponse = httpclient.execute(targetHost, httpGet); Example Following example demonstrates how to send a HTTP request to a server via proxy. In this example, we are sending a HTTP GET request to google.com via localhost. We have printed the headers of the response and the body of the response. import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.routing.HttpRoutePlanner; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.DefaultProxyRoutePlanner; import org.apache.http.util.EntityUtils; public class RequestViaProxyExample { public static void main(String args[]) throws Exception{ //Creating an HttpHost object for proxy HttpHost proxyhost = new HttpHost(“localhost”); //Creating an HttpHost object for target HttpHost targethost = new HttpHost(“google.com”); //creating a RoutePlanner object HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyhost); //Setting the route planner to the HttpClientBuilder object HttpClientBuilder clientBuilder = HttpClients.custom(); clientBuilder = clientBuilder.setRoutePlanner(routePlanner); //Building a CloseableHttpClient CloseableHttpClient httpclient = clientBuilder.build(); //Creating an HttpGet object HttpGet httpget = new HttpGet(“/”); //Executing the Get request HttpResponse httpresponse = httpclient.execute(targethost, httpget); //Printing the status line System.out.println(httpresponse.getStatusLine()); //Printing all the headers of the response Header[] headers = httpresponse.getAllHeaders(); for (int i = 0; i < headers.length; i++) { System.out.println(headers[i]); } //Printing the body of the response HttpEntity entity = httpresponse.getEntity(); if (entity != null) { System.out.println(EntityUtils.toString(entity)); } } } Output On executing, the above program generates the following output − HTTP/1.1 200 OK Date: Sun, 23 Dec 2018 10:21:47 GMT Server: Apache/2.4.9 (Win64) PHP/5.5.13 Last-Modified: Tue, 24 Jun 2014 10:46:24 GMT ETag: “2e-4fc92abc3c000″ Accept-Ranges: bytes Content-Length: 46 Content-Type: text/html <html><body><h1>It works!</h1></body></html> Print Page Previous Next Advertisements ”;

Multipart Upload

Apache HttpClient – Multipart Upload ”; Previous Next Using HttpClient, we can perform Multipart upload, i.e., we can upload larger objects in smaller parts. In this chapter, we demonstrate the multipart upload in HTTP client by uploading a simple text file. In general, any multipart upload contains three parts. Initiation of the upload Uploading the object parts Completing the Multipart upload For the multipart upload using HttpClient, we need to follow the below steps − Create a multipart builder. Add desired parts to it. Complete the build and obtain a multipart HttpEntity. Build request by setting the above muti-part entity. Execute the request. Following are the steps to upload a multipart entity using the HttpClient library. Step 1 – Create an HttpClient object The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface. Using this method, create an HttpClient object − //Creating CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); Step 2 – Create a FileBody object FileBody class represents the binary body part backed by a file. Instantiate this class by passing a File object and a ContentType object representing the type of the content. //Creating a File object File file = new File(“sample.txt”); //Creating the FileBody object FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY); Step 3 – Create a MultipartEntityBuilder The MultipartEntityBuilder class is used to build the multi-part HttpEntity object. Create its object using the create() method (of the same class). //Creating the MultipartEntityBuilder MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create(); Step 4 – Set the mode A MultipartEntityBuilder has three modes: STRICT, RFC6532, and BROWSER_COMPATIBLE. Set it to the desired mode using the setMode() method. //Setting the mode entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); Step 5 – Add various the desired parts Using the methods addTextBody(), addPart() and, addBinaryBody(), you can add simple text, files, streams, and other objects to a MultipartBuilder. Add the desired contents using these methods. //Adding text entitybuilder.addTextBody(“sample_text”, “This is the text part of our file”); //Adding a file entitybuilder.addBinaryBody(“image”, new File(“logo.png”)); Step 6 – Building single entity You can build all these parts to a single entity using the build() method of the MultipartEntityBuilder class. Using this method, build all the parts into a single HttpEntity. //Building a single entity using the parts HttpEntity mutiPartHttpEntity = entityBuilder.build(); Step 7 – Create a RequestBuilder object The class RequestBuilder is used to build request by adding parameters to it. If the request is of type PUT or POST, it adds the parameters to the request as URL encoded entity. Create a RequestBuilder object (of type POST) using the post() method. And pass the Uri to which you wanted to send the request it as a parameter. //Building the post request object RequestBuilder reqbuilder = RequestBuilder.post(“http://httpbin.org/post”); Step 8 – Set the entity object to the RequestBuilder Set the above created multipart entity to the RequestBuilder using the setEntity() method of the RequestBuilder class. //Setting the entity object to the RequestBuilder reqbuilder.setEntity(mutiPartHttpEntity); Step 9 – Build the HttpUriRequest Build a HttpUriRequest request object using the build() method of the RequestBuilder class. //Building the request HttpUriRequest multipartRequest = reqbuilder.build(); Step 10 – Execute the request Using the execute() method, execute the request built in the previous step (bypassing the request as a parameter to this method). //Executing the request HttpResponse httpresponse = httpclient.execute(multipartRequest); Example Following example demonstrates how to send a multipart request using the HttpClient library. In this example, we are trying to send a multipart request backed by a file. import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; public class MultipartUploadExample { public static void main(String args[]) throws Exception{ //Creating CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); //Creating a file object File file = new File(“sample.txt”); //Creating the FileBody object FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY); //Creating the MultipartEntityBuilder MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create(); //Setting the mode entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //Adding text entitybuilder.addTextBody(“sample_text”, “This is the text part of our file”); //Adding a file entitybuilder.addBinaryBody(“image”, new File(“logo.png”)); //Building a single entity using the parts HttpEntity mutiPartHttpEntity = entitybuilder.build(); //Building the RequestBuilder request object RequestBuilder reqbuilder = RequestBuilder.post(“http://httpbin.org/post”); //Set the entity object to the RequestBuilder reqbuilder.setEntity(mutiPartHttpEntity); //Building the request HttpUriRequest multipartRequest = reqbuilder.build(); //Executing the request HttpResponse httpresponse = httpclient.execute(multipartRequest); //Printing the status and the contents of the response System.out.println(EntityUtils.toString(httpresponse.getEntity())); System.out.println(httpresponse.getStatusLine()); } } Output On executing, the above program generates the following output − { “args”: {}, “data”: “”, “files”: { “image”: “data:application/octets66PohrH3IWNk1FzpohfdXPIfv9X3490FGcuXsHn9X0piCwomF/xdgADZ9GsfSyvLYAAAAAE lFTkSuQmCC” }, “form”: { “sample_text”: “This is the text part of our file” }, “headers”: { “Accept-Encoding”: “gzip,deflate”, “Connection”: “close”, “Content-Length”: “11104”, “Content-Type”: “multipart/form-data; boundary=UFJbPHT7mTwpVq70LpZgCi5I2nvxd1g-I8Rt”, “Host”: “httpbin.org”, “User-Agent”: “Apache-HttpClient/4.5.6 (Java/1.8.0_91)” }, “json”: null, “origin”: “117.216.245.180”, “url”: “http://httpbin.org/post” } HTTP/1.1 200 OK Print Page Previous Next Advertisements ”;

Multiple Threads

Apache HttpClient – Multiple Threads ”; Previous Next A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources. You can execute requests from multiple threads by writing a multithreaded HttpClient program. If you want to execute multiple client requests from threads consecutively, you need to create a ClientConnectionPoolManager. It maintains a pool of HttpClientConnections and serves multiple requests from threads. The connections manager pools the connections based on the route. If the manager has connections for a particular route, then it serves new requests in those routes by leasing an existing connection from the pool, instead of creating a new one. Follow the steps to execute requests from multiple threads − Step 1 – Creating the Client Connection Pool Manager Create the Client Connection Pool Manager by instantiating the PoolingHttpClientConnectionManager class. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); Step 2 – Set the maximum number of connections Set the maximum number of connections in the pool using the setMaxTotal() method. //Set the maximum number of connections in the pool connManager.setMaxTotal(100); Step 3 – Create a ClientBuilder Object Create a ClientBuilder Object by setting the connection manager using the setConnectionManager() method as shown below − HttpClientBuilder clientbuilder = HttpClients.custom().setConnectionManager(connManager); Step 4 – Create the HttpGet request objects Instantiate the HttpGet class by passing the desired URI to its constructor as a parameter. HttpGet httpget1 = new HttpGet(“URI1”); HttpGet httpget2 = new HttpGet(“URI2”); . . . . . . . . . . . . Step 5 – Implementing the run method Make sure that you have created a class, made it a thread (either by extending the thread class or, by implementing the Runnable interface) and implemented the run method. public class ClientMultiThreaded extends Thread { public void run() { //Run method implementation . . . . . . . . . . } } Step 6 – Create Thread objects Create thread objects by instantiating the Thread class (ClientMultiThreaded) created above. Pass a HttpClient object, respective HttpGet object and, an integer representing the ID to these threads. ClientMultiThreaded thread1 = new ClientMultiThreaded(httpclient,httpget1, 1); ClientMultiThreaded thread2 = new ClientMultiThreaded(httpclient,httpget2, 2); . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Step 7 – Start and join the threads Start all the threads using start() method and join them using the join method(). thread1.start(); thread2.start(); . . . . . . . . thread1.join(); thread2.join(); . . . . . . . . . . . . Step 8 – Run method implementation Within the run method, execute the request, retrieve the response and print the results. Example Following example demonstrates the execution of HTTP requests simultaneously from multiple threads. In this example, we are trying to execute various requests from various threads and trying to print the status, and the number of bytes read by each client. import org.apache.http.HttpEntity; 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.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.util.EntityUtils; public class ClientMultiThreaded extends Thread { CloseableHttpClient httpClient; HttpGet httpget; int id; public ClientMultiThreaded(CloseableHttpClient httpClient, HttpGet httpget, int id) { this.httpClient = httpClient; this.httpget = httpget; this.id = id; } @Override public void run() { try{ //Executing the request CloseableHttpResponse httpresponse = httpClient.execute(httpget); //Displaying the status of the request. System.out.println(“status of thread “+id+”:”+httpresponse.getStatusLine()); //Retrieving the HttpEntity and displaying the no.of bytes read HttpEntity entity = httpresponse.getEntity(); if (entity != null) { System.out.println(“Bytes read by thread thread “+id+”: “+EntityUtils.toByteArray(entity).length); } }catch(Exception e) { System.out.println(e.getMessage()); } } public static void main(String[] args) throws Exception { //Creating the Client Connection Pool Manager by instantiating the PoolingHttpClientConnectionManager class. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); //Set the maximum number of connections in the pool connManager.setMaxTotal(100); //Create a ClientBuilder Object by setting the connection manager HttpClientBuilder clientbuilder = HttpClients.custom().setConnectionManager(connManager); //Build the CloseableHttpClient object using the build() method. CloseableHttpClient httpclient = clientbuilder.build(); //Creating the HttpGet requests HttpGet httpget1 = new HttpGet(“https://www.tutorialspoint.com/”); HttpGet httpget2 = new HttpGet(“http://www.google.com/”); HttpGet httpget3 = new HttpGet(“https://www.qries.com/”); HttpGet httpget4 = new HttpGet(“https://in.yahoo.com/”); //Creating the Thread objects ClientMultiThreaded thread1 = new ClientMultiThreaded(httpclient,httpget1, 1); ClientMultiThreaded thread2 = new ClientMultiThreaded(httpclient,httpget2, 2); ClientMultiThreaded thread3 = new ClientMultiThreaded(httpclient,httpget3, 3); ClientMultiThreaded thread4 = new ClientMultiThreaded(httpclient,httpget4, 4); //Starting all the threads thread1.start(); thread2.start(); thread3.start(); thread4.start(); //Joining all the threads thread1.join(); thread2.join(); thread3.join(); thread4.join(); } } Output On executing, the above program generates the following output − status of thread 1: HTTP/1.1 200 OK Bytes read by thread thread 1: 36907 status of thread 2: HTTP/1.1 200 OK Bytes read by thread thread 2: 13725 status of thread 3: HTTP/1.1 200 OK Bytes read by thread thread 3: 17319 status of thread 4: HTTP/1.1 200 OK Bytes read by thread thread 4: 127018 Print Page Previous Next Advertisements ”;

User Authentication

Apache HttpClient – User Authentication ”; Previous Next Using HttpClient, you can connect to a website which needed username and password. This chapter explains, how to execute a client request against a site that asks for username and password. Step 1 – Create a CredentialsProvider object The CredentialsProvider Interface maintains a collection to hold the user login credentials. You can create its object by instantiating the BasicCredentialsProvider class, the default implementation of this interface. CredentialsProvider credentialsPovider = new BasicCredentialsProvider(); Step 2 – Set the Credentials You can set the required credentials to the CredentialsProvider object using the setCredentials() method. This method accepts two objects as given below − AuthScope object − Authentication scope specifying the details like hostname, port number, and authentication scheme name. Credentials object − Specifying the credentials (username, password). Set the credentials using the setCredentials() method for both host and proxy as shown below − credsProvider.setCredentials(new AuthScope(“example.com”, 80), new UsernamePasswordCredentials(“user”, “mypass”)); credsProvider.setCredentials(new AuthScope(“localhost”, 8000), new UsernamePasswordCredentials(“abc”, “passwd”)); Step 3 – Create a HttpClientBuilder Object Create a HttpClientBuilder using the custom() method of the HttpClients class. //Creating the HttpClientBuilder HttpClientBuilder clientbuilder = HttpClients.custom(); Step 4 – Set the credentialsPovider You can set the above created credentialsPovider object to a HttpClientBuilder using the setDefaultCredentialsProvider() method. Set the CredentialProvider object created in the previous step to the client builder by passing it to the CredentialsProvider object() method as shown below. clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider); Step 5 – Build the CloseableHttpClient Build the CloseableHttpClient object using the build() method of the HttpClientBuilder class. CloseableHttpClient httpclient = clientbuilder.build() Step 6 – Create a HttpGet object and execute it Create a HttpRequest object by instantiating the HttpGet class. Execute this request using the execute() method. //Creating a HttpGet object HttpGet httpget = new HttpGet(“https://www.tutorialspoint.com/ “); //Executing the Get request HttpResponse httpresponse = httpclient.execute(httpget); Example Following is an example program which demonstrates the execution of a HTTP request against a target site that requires user authentication. import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; public class UserAuthenticationExample { public static void main(String args[]) throws Exception{ //Create an object of credentialsProvider CredentialsProvider credentialsPovider = new BasicCredentialsProvider(); //Set the credentials AuthScope scope = new AuthScope(“https://www.tutorialspoint.com/questions/”, 80); Credentials credentials = new UsernamePasswordCredentials(“USERNAME”, “PASSWORD”); credentialsPovider.setCredentials(scope,credentials); //Creating the HttpClientBuilder HttpClientBuilder clientbuilder = HttpClients.custom(); //Setting the credentials clientbuilder = clientbuilder.setDefaultCredentialsProvider(credentialsPovider); //Building the CloseableHttpClient object CloseableHttpClient httpclient = clientbuilder.build(); //Creating a HttpGet object HttpGet httpget = new HttpGet(“https://www.tutorialspoint.com/questions/index.php”); //Printing the method used System.out.println(httpget.getMethod()); //Executing the Get request HttpResponse httpresponse = httpclient.execute(httpget); //Printing the status line System.out.println(httpresponse.getStatusLine()); int statusCode = httpresponse.getStatusLine().getStatusCode(); System.out.println(statusCode); Header[] headers= httpresponse.getAllHeaders(); for (int i = 0; i<headers.length;i++) { System.out.println(headers[i].getName()); } } } Output On executing, the above program generates the following output. GET HTTP/1.1 200 OK 200 Print Page Previous Next Advertisements ”;

Environment Setup

Apache HttpClient – Environment Setup ”; Previous Next In this chapter, we will explain how to set an environment for HttpClient in Eclipse IDE. Before proceeding with the installation, make sure that you already have Eclipse installed in your system. If not, download and install Eclipse. For more information on Eclipse, please refer to our Eclipse Tutorial. Step 1 – Download the dependency JAR file Open the official homepage of the HttpClient (components) website and go to the download page Then, download the latest stable version of HttpClient. Here, throughout the tutorial, we are using the version 4.5.6 hence download the file 4.5.6.zip. Within the downloaded folder, you will find a folder named lib and this contains the required Jar files that are to be added in the classpath of your project, to work with HttpClient. Step 2 – Create a project and set build path Open eclipse and create a sample project. Right click on the project select the option Build Path → Configure Build Path as shown below. In the Java Build Path frame in the Libraries tab, click on Add External JARs. And select all the jar files in the lib folder and, click on Apply and Close. You are all set to work with HttpClient library in eclipse. Print Page Previous Next Advertisements ”;