DEV Community

loading...
Cover image for Simplify HTTP requests on mobile with these libraries

Simplify HTTP requests on mobile with these libraries

theotherdevs profile image TheOtherDev/s ・3 min read

I’m a simple guy. When coding is hard, I strive to make it as easy as possibile. Except for HTTP requests…

I’ve been working on mobile for 8 years, and I’m still using HttpsURLConnection and InputStream on Android, even if there are plenty of libraries ready to make HTTP requests easier and drastically reduce boilerplate code. Let’s see some of the most used on Android, and the ONLY used on iOS:

OkHttp

This library created by the nice guys of Square (the same people that brought us Picasso) is an absolute breeze to use. OkHttp doesn’t need any complex initialization process, and a GET request looks like this:

OkHttpClient client = new OkHttpClient(); 
String run(String url) throws IOException { 
    Request request = new Request.Builder() 
    .url(url) 
    .build(); 
try (Response response = client.newCall(request).execute()) { 
   return response.body().string(); 
    } 
}
Enter fullscreen mode Exit fullscreen mode

Even POST requests are easy-peasy:

public static final MediaType JSON = 
MediaType.get("application/json; charset=utf-8"); 
OkHttpClient client = new OkHttpClient(); 
String post(String url, String json) throws IOException { 
    RequestBody body = RequestBody.create(json, JSON); 
    Request request = new Request.Builder() 
       .url(url) 
       .post(body) 
       .build(); 
try (Response response = client.newCall(request).execute()) { 
    return response.body().string(); } 
}
Enter fullscreen mode Exit fullscreen mode

OkHttp depends on Square’s Okio and Kotlin to provide great performance and backwards-compatibility. It’s really easy to use, but it can be hard if you have to work on complicated stuff like mid-connection checks or proxy tunneling. Plus, it won’t chart the results directly into objects. It has been developed with a simplicity mind-set. You can find more about OkHttp here.

Retrofit

Retrofit, created by the guys at Square too, is vey different from OkHttp. Indeed, it uses an annotation method of interfaces which represents the services to use. For example, if we want a list of “Users” data, we should implement this interface:

public interface UserRestService { 
    @GET("users") 
    Call<List<User>> listUsers(); 
}
Enter fullscreen mode Exit fullscreen mode

Then initialize the library like this:

Retrofit retrofit = new Retrofit.Builder().baseUrl("SOME_URL").build();
UserService userService = retrofit.create(UserService.class);
Enter fullscreen mode Exit fullscreen mode

To have our list of users we should simply call syncronously:

Copy codeList<User>> userList = userService.listUsers().execute().body();
Enter fullscreen mode Exit fullscreen mode

or asyncronously:

Callback <List<User>> callback;
userService.listUsers().enqueue(callback);
Enter fullscreen mode Exit fullscreen mode

It’s definitely a different approach from the other library. Retrofit has no much control over what the library is doing, but it’s nice to have a direct access to the data class. You can find more about Retrofit here.

Alamofire

This library doesen’t need any presentation, is literally the most used HTTP request tool used on iOS. Easy for simple and complex things and complete in every respect. A simple GET request is just 3 lines of code:

AF.request("https://httpbin.org/get").response { response in
    debugPrint(response)
}
Enter fullscreen mode Exit fullscreen mode

If you need to specify more parameters don’t worry, you can add whathever you like:

open func request<Parameters: Encodable>(
  _convertible: URLConvertible,
  HTTPMethod = .get,
  parameters: Parameters? = nil,
  encoder: ParameterEncoder =URLEncodedFormParameterEncoder.default,
  headers: HTTPHeaders? = nil,
  interceptor: RequestInterceptor? = nil) -> DataRequest
Enter fullscreen mode Exit fullscreen mode

Based on Swift and constantly updated, it’s probably the most used library on iOS.
Don’t worry, this is the best and only library you can use for HTTP requests. You can find more info on Alamofire here.

Now the hot question: what’s the best library to use?
On iOS it’s very easy. Alamofire is the standard de facto for HTTP requests on iOS so, don’t be afraid to use it. On Android the answer is a little bit more complex. Let’s say that both options are perfectly usable and there’s no real “bad” choice. Find to one you like the most based on your needs. Remember that someone is still using HttpsURLConnection class...

Discussion (0)

Forem Open with the Forem app