1

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.

Mathias
  • 3,879
  • 5
  • 36
  • 48

2 Answers2

0

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'.

Nayan Srivastava
  • 3,655
  • 3
  • 27
  • 49
  • Well, i have looked around, but found no good way to set the parameters i need, most importantly specify the charset to use for basic auth credentials. HttpClient is the only place where i've found it. – Mathias Aug 01 '16 at 16:48
  • How about this in OKHttp ```Request.Builder reqBuilder = new Request.Builder().addHeader("Accept-Charset", "utf-8")```. You can have other charsets as well. – Nayan Srivastava Aug 01 '16 at 16:53
0

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)
naveejr
  • 735
  • 1
  • 15
  • 31