Skip to content
Ludovic ROLAND edited this page Mar 26, 2018 · 6 revisions

Download License: MIT TeamCity status

Using the okhttp implementation in your project

Add the following in your app module build.gradle file:

dependencies
{ 
  implementation ("com.smartnsoft:okhttpwebservicecaller:${latest.version}")
}

Create a simple WebServiceCaller client for your app

The minimal code

In order to create a WebServiceCaller client for your Android project, just extends from the OkHttpClientWebServiceCaller and implement the following methods:

  • getUrlEncoding: this method returns the charset to use for encoding the URI parameters ;
  • getContentEncoding: this method returns the charset to use for decoding the web service requests content.

You also have to the create a constructor and call the super one with 3 parameters :

  • readTimeOutInMilliseconds
  • connectTimeOutInMilliseconds
  • acceptGzip

In order to optimize your application, we recommand to implement the singleton pattern. For example:

public final class ExempleServices
    extends OkHttpClientWebServiceCaller
{

  private static volatile ExempleServices instance;

  // We accept the "out-of-order writes" case
  public static ExempleServices getInstance()
  {
    if (instance == null)
    {
      synchronized (ExempleServices.class)
      {
        if (instance == null)
        {
          instance = new ExempleServices();
        }
      }
    }

    return instance;
  }

  private ExempleServices()
  {
    super(5_000, 5_000, true);
  }

  @Override
  protected String getUrlEncoding()
  {
    return Encoding.UTF_8.toString();
  }

  @Override
  protected String getContentEncoding()
  {
    return Encoding.ISO_8859_1.toString();
  }

}

Other features

By default, the component will create his own instance of the Square okhttp client, but you can work with your own overriding the computeHttpClient method.

@Override
protected Builder computeHttpClient()
{
  return super.computeHttpClient();
}

By default, the component will recreate a new okhttp client for each request but in order to optimize the performance of your app, you can indicate to the component to reuse the same http client with the ReuseOkHttpClient annotation:

@ReuseOkHttpClient
public final class ExempleServices
    extends OkHttpClientWebServiceCaller
{
  //
}

How to do a request ?

Note: The component run all its HTTP requests in the calling thread!

With no cache

A first simple GET request

To run a simple HTTP GET method request, just use the runRequest(String) method with the URL to call as parameter. This method returns a HttpResponse object that wraps the headers and the input stream resulting to the HTTP request, which are taken from the response.

final HttpResponse httpResponse = runRequest("https://jsonplaceholder.typicode.com/posts/1");

Note: This runRequest(String) method throws a CallException if the status code of the HTTP response does not belong to the HttpURLConnection#HTTP_OK, HttpURLConnection#HTTP_MULT_CHOICE range. Also if a connection issue occurred: the exception will embed the cause of the exception. If the isConnected() method returns false, no request will be attempted and a CallException exception will be thrown (embedding a UnknownHostException exception)

The component also provides tools in order to compute and encode a URI from its path elements. Just use the computeUri(String, String, Map) method :

final Map<String, String> parameters = new HashMap<>();
parameters.put("userId", userId);

final HttpResponse httpResponse = runRequest(computeUri("https://jsonplaceholder.typicode.com", "posts", parameters));

Other HTTP verbs

The component supports followings HTTP verbs :

  • GET
  • POST
  • PUT
  • DELETE
  • PATCH
  • HEAD
  • OPTIONS

To run a HTTP request with the choosent HTTP verb, just use the runRequest(String, CallType, Map<String, String>, Map<String, String>, String, List<MultipartFile>) with the appropriate parameters. This method returns a HttpResponse object that wraps the headers and the input stream resulting to the HTTP request, which are taken from the response.

final Map<String, String> parameters = new HashMap<>();
parameters.put("title", title);
parameters.put("body", body);
parameters.put("userId", userId);

final Map<String, String> headers = new HashMap<>();
headers.put("Content-type", "application/json; charset=UTF-8");

final HttpResponse httpResponse = runRequest("https://jsonplaceholder.typicode.com/posts", CallType.Post, headers, parameters, null, null);

With cache

//TODO

Cache local data

//TODO

How to use Jackson ?

//TODO

Possible optimization

You can optimize the behavior on the component listening for the network changes and use the setConnected(boolean) method in order to indicate that no Internet connectivity is available, or that the connectivity has been restored. The initial value is true. If the value is false, no request will be attempted and a CallException exception will be thrown (embedding a UnknownHostException exception)