A full fledged HttpClient
A client program which can establish a connection with web server over HTTP and then send request & receive response messages.
Code Explanation
java.net package provides interfaces and classes to establish comunication link between application and URL. Following steps are involved when java.net.HttpURLConnection is used for communication over HTTP:
- Create URL
- Call openConnection() on URL to get a connection
- Add necessary connection properties and request headers
- Establish the actual connection by calling connect() method on HttpURLConnection
- Read response headers from connection
- Read the response as input stream obtained from connection
At the begining HTTP proxy connection properties are set in java.lang.System. This is required only when a proxy connection is used for communication link.
28 /** 29 * Sets proxy connection related properties. 30 */ 31 private void setupProxy() { 32 // Http proxy properties 33 System.getProperties().put("http.proxyHost", "URL"); 34 System.getProperties().put("http.proxyPort", "Port"); 35 // User name and password are optional 36 System.getProperties().put("http.proxyUser", "UserName"); 37 System.getProperties().put("http.proxyPassword", "Password"); 38 }
As described above, sendRequest() method sequentially calls methods to create URL, get Http URL connection, setup connection properties, add request headers, establish actual connection and finally receives Http response.
50 /** 51 * Opens a connection and sends Http request to given URL. 52 * @param url URL to be invoked. 53 * @return Response as a stream. 54 */ 55 private InputStream sendRequest(String url) { 56 try { 57 URL urlInstance = new URL(url); 58 HttpURLConnection connection = (HttpURLConnection) urlInstance. 59 openConnection(); 60 // Set timeout in milliseconds 61 connection.setConnectTimeout(20000); 62 // Set request headers 63 addRequestHeaders(connection); 64 // Establiish a connection 65 connection.connect(); 66 // Read response status and headers 67 readResponseStatusAndHeaders(connection); 68 // Return response 69 return connection.getInputStream(); 70 } catch (IOException ex) { 71 ex.printStackTrace(); 72 } 73 return null; 74 }
Adds Http request headers to connection. Get the complete list of request headers from here.
76 /** 77 * Adds request headers to connection. 78 * @param connection Http URL connection instance. 79 */ 80 private void addRequestHeaders(HttpURLConnection connection) { 81 connection.addRequestProperty("Accept", "text/plain"); 82 connection.addRequestProperty("Accept-Language", "en"); 83 connection.addRequestProperty("Cache-Control", "no-cache"); 84 }
Gets response code, response message and response headers from connection. Get the complete list of response headers from here.
86 /** 87 * Reads response code, message and header fields. 88 * @param connection Http URL connection instance. 89 * @throws IOException If an error occrred while connecting to server. 90 */ 91 private void readResponseStatusAndHeaders(HttpURLConnection connection) throws 92 IOException { 93 System.out.println("Response code: " + connection.getResponseCode()); 94 System.out.println( 95 "Response message: " + connection.getResponseMessage()); 96 System.out.println("Response header: Content-Length: " + connection. 97 getHeaderField("Content-Length")); 98 }
Finally, get response data from input stream obtained from connection.
100 /** 101 * Prints the response to console. 102 * @param response Response stream. 103 */ 104 private void processResponse(InputStream response) { 105 if (response == null) { 106 System.out.println("No or blank response received"); 107 } else { 108 StringBuilder data = new StringBuilder(); 109 try { 110 int bufferSize = 2048; 111 byte[] inputData = new byte[bufferSize]; 112 int count = 0; 113 while ((count = response.read(inputData, 0, bufferSize)) != -1) { 114 data.append(new String(inputData, 0, count, "UTF-8")); 115 } 116 } catch (IOException ex) { 117 ex.printStackTrace(); 118 } 119 System.out.println("Data received: " + data.toString()); 120 } 121 } 122 } 123 124