Web services using Retrofit 2.0
Posted By : Jitendra Negi | 27-Jun-2016
To start implementing retrofit 2.0, firstly you have to add retrofit library to your projects.
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
Add these lines to your app build.Now Sync your project after adding both library.we need following permission in order to access network state. Add following permission to your AndroidManifest.xml file.
now you need a service generator class to create service
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ServiceGenerator {
public static <object> createService(Class <object>serviceClass, String baseUrl) {
//this.baseUrl = baseUrl;
OkHttpClient httpClient = new OkHttpClient();
Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.client(httpClient.newBuilder().connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS).build()).build();
return retrofit.create(serviceClass);
}
}
Than create a interface for network call.
public interface UserConnection {
@Headers({
"Content-type: application/json",
})
@POST(Config.LOGIN)
Call<loginresponse> requestLogin(@Body JsonObject jsonObject);
}
now you can call this interface to communicate with server.
THANKS
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Jitendra Negi
Jitendra is an Android application developer, specializing in native Android apps. He knows a lot about architecture, communications, jni material design and a lot of other things.