Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Wrapping Apache HTTPClient

Lukas Rieder
November 07, 2013

Wrapping Apache HTTPClient

This talk gives you an insight on how to wrap a Java library nicely for use in JRuby.
Presented on 7 Nov 2013 at the Berlin Ruby User Group.

Source Code: https://github.com/Overbryd/http_client
Gem: http://rubygems.org/gems/http_client

Lukas Rieder

November 07, 2013
Tweet

More Decks by Lukas Rieder

Other Decks in Technology

Transcript

  1. import org.apache.http.impl.client.HttpClients import org.apache.http.impl.conn.BasicHttpClientConnectionManager import org.apache.http.impl.conn.PoolingHttpClientConnectionManager import org.apache.http.client.methods.HttpGet import org.apache.http.client.methods.HttpPost

    import org.apache.http.client.methods.HttpPut import org.apache.http.client.methods.HttpPatch import org.apache.http.client.methods.HttpDelete import org.apache.http.client.methods.HttpHead import org.apache.http.client.methods.HttpOptions import org.apache.http.client.config.RequestConfig import org.apache.http.entity.StringEntity import org.apache.http.client.entity.UrlEncodedFormEntity import org.apache.http.client.entity.GzipDecompressingEntity import org.apache.http.client.entity.DeflateDecompressingEntity import org.apache.http.message.BasicNameValuePair import org.apache.http.entity.ContentType import org.apache.http.util.EntityUtils import org.apache.http.HttpException import org.apache.http.conn.ConnectTimeoutException import java.io.IOException import java.net.SocketTimeoutException import java.util.concurrent.TimeUnit
  2. J

  3. def create_connection_manager(options) options[:use_connection_pool] ? create_pooling_connection_manager(options) : BasicHttpClientConnectionManager.new end ! def

    create_pooling_connection_manager(options) connection_manager = PoolingHttpClientConnectionManager.new connection_manager.max_total = options[:max_connections] max_per_route = options[:max_connections_per_route] || \ options[:max_connections] connection_manager.default_max_per_route = max_per_route end
  4. def execute(request) retries = max_retries begin closeable_response = client.execute(request) response_class.new(closeable_response)

    rescue ConnectTimeoutException, SocketTimeoutException => e retry if (retries -= 1) > 0 raise Timeout, "#{e.message}" rescue IOException => e retry if (retries -= 1) > 0 raise IOError, "#{e.message}" rescue HttpException => e raise Error, "#{e.message}" ensure closeable_response.close if closeable_response end end
  5. def read_body(closeable_response) return "" unless entity = closeable_response.entity return ""

    unless entity.content_length > 0 if content_encoding = entity.content_encoding entity = case content_encoding.value when "gzip", "x-gzip" then GzipDecompressingEntity.new(entity) when "deflate" then DeflateDecompressingEntity.new(entity) else entity end end EntityUtils.to_string(entity, "UTF-8") end end