HttpClient is removed from Android 6.0, how do i use it with RestTemplate?

729 Views Asked by At

I have the need to use the HttpClient to set certain parameters while using Spring's RestTemplate.

I currently do this via:

HttpClient httpClient = new HttpClient();
httpClient.getParams().setSoTimeout(prefs.getServerTimeout());
httpClient.getParams().setConnectionManagerTimeout(3000);
httpClient.getParams().setContentCharset("UTF-8");
httpClient.getParams().setCredentialCharset("ISO-8859-1", )
...
CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory(httpClient);
requestFactory.setReadTimeout(prefs.getServerTimeout());

RestTemplate restTemplate = new RestTemplate(requestFactory);

The HttpClient currently used everywhere, and for example in the

HttpComponentsClientHttpRequestFactory.getHttpClient()

Is pointing to the deprecated one shipped with Android.

Since it's deprecated, and removed from Android in 6.0, how do i go about continuing to use a HttpClient object with RestTemplate?

Since they share the same package (org.apache.http.client), i'm not sure how to make this work in pre/post 6.0.

(I tried using httpclient-android and HttpComponentsClientHttpRequestFactory without setting HttpClient, and it then seems to be using CloseableHttpClient. But the method signature is the deprecated HttpClient as mentioned.)

Pointers would be much appreciated.

2

There are 2 best solutions below

2
Nayan Srivastava On

You can add it's dependency explicitly in gradle or add jar but try considering modern options like volley 'com.android.volley:volley:1.0.0' or okHttp 'com.squareup.okhttp3:okhttp:3.4.1' or you can use Rest-Template for android 'org.springframework.android:spring-android-rest-template:2.0.0.M3'.

0
naveejr On

I think you can use SimpleClientHttpRequestFactory from springframework (org.springframework.http.client.SimpleClientHttpRequestFactory) .

override the prepareConnection method to set timeout and other parameters.

public class MySimpleClientHttpRequestFactory  extends SimpleClientHttpRequestFactory {

   @Override
   protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
    super.prepareConnection(connection, httpMethod);
    connection.setConnectTimeout(5000);
    connection.setReadTimeout(10000);
   }
}

Then set it to RestTemplate.

SimpleClientHttpRequestFactory factory = new MySimpleClientHttpRequestFactory();
RestTemplate template = new RestTemplate(factory)