Handling deprecated warnings in Apache’s HttpClient and HttpParams

If you encounter deprecation warning in Apache common HttpComponent 4.3 and above, here’s an example how to fix this.

This would be the old, deprecated code:

		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
		HttpConnectionParams.setSoTimeout(httpParams, 1000);
		DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
		httpClient.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
		httpClient.getParams().setParameter("http.socket.timeout", new Integer(1000));
		httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
		HttpGet getRequest = new HttpGet(url);
		getRequest.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Firefox/3.6.13");
		getRequest.getParams().setParameter("http.socket.timeout", new Integer(5000));
		try {

			// Execute the method.
			HttpResponse response = httpClient.execute(getRequest);
			int statusCode = response.getStatusLine().getStatusCode();

			if (statusCode != HttpStatus.SC_OK) {
				throw new IllegalStateException("Method failed: " + response.getStatusLine());
			}

			BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

			StringBuffer buf = new StringBuffer();
			String output;
			while ((output = br.readLine()) != null) {
				buf.append(output);
			}

			content = buf.toString();

		} catch (Exception e) {
			throw e;
		} finally {
			// Release the connection.
			httpClient.getConnectionManager().shutdown();
		}

And this is the same code block, accommodating the new Builder pattern:


		CloseableHttpClient httpClient = HttpClients.createDefault();
		
        // Request configuration can be overridden at the request level.
        // They will take precedence over the one set at the client level.
        RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(5000)
            .setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000)
            .build();
        
		HttpGet httpget = new HttpGet(url);
        
        httpget.setConfig(requestConfig);
        httpget.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Firefox/3.6.13");

     // Execution context can be customized locally.
        HttpClientContext context = HttpClientContext.create();
        // Contextual attributes set the local context level will take
        // precedence over those set at the client level.
        context.setAttribute("http.protocol.version", HttpVersion.HTTP_1_1);

		try {

			// Execute the method.
			HttpResponse response = httpClient.execute(httpget);
			int statusCode = response.getStatusLine().getStatusCode();

			if (statusCode != HttpStatus.SC_OK) {
				throw new IllegalStateException("Method failed: " + response.getStatusLine());
			}

			BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

			StringBuffer buf = new StringBuffer();
			String output;
			while ((output = br.readLine()) != null) {
				buf.append(output);
			}

			content = buf.toString();

		} catch (Exception e) {
			throw e;
		} finally {
			// Release the connection.
			httpClient.close();
		}

A more in depth example of the various options such as Pooling, ConnectionManagemers and such is here:

http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientConfiguration.java

Advertisements
This entry was posted in Enterprise Java. Bookmark the permalink.

2 Responses to Handling deprecated warnings in Apache’s HttpClient and HttpParams

  1. kuu6 says:

    Thank you, this has been useful 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s