First of all, add gradle dependency
dependencies {
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'}
Check for updated version. Make one class that handle retrofit stuff NetCall.java
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import okhttp3.OkHttpClient; import okhttp3.ResponseBody; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.Body; import retrofit2.http.POST; /** * Created by axay on 09-05-2016. */public class NetCall { String baseUrl = "http://example.com/service/"; public Request request; public Call<JsonObject> featuredPlaylist(JsonObject jsonObject) { return request.featuredPlaylist(jsonObject); } public Call<JsonObject> allUserPlaylist(JsonObject jsonObject) { return request.allUserPlaylist(jsonObject); } public interface Request{ @POST("library/featuredplaylist.php") Call<JsonObject> featuredPlaylist(@Body JsonObject jsonObject); @POST("library/alluserplaylist.php") Call<JsonObject> allUserPlaylist(@Body JsonObject jsonObject); } public NetCall(){ Gson gson = new GsonBuilder().disableHtmlEscaping().create(); HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .client(client) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); request = retrofit.create(Request.class); } }Now call this wherever you want. Suppose In MainActivity.javaimport android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.google.gson.JsonObject; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); JsonObject jsonObject = new JsonObject(); new NetCall().featuredPlaylist(jsonObject).enqueue(new Callback<JsonObject>() { @Override public void onResponse(Call<JsonObject> call, Response<JsonObject> response) { JsonObject jsonObject1 = response.body(); } @Override public void onFailure(Call<JsonObject> call, Throwable t) { } }); new NetCall().allUserPlaylist(jsonObject).enqueue(new Callback<JsonObject>() { @Override public void onResponse(Call<JsonObject> call, Response<JsonObject> response) { JsonObject jsonObject1 = response.body(); } @Override public void onFailure(Call<JsonObject> call, Throwable t) { } }); } }
Now Parse JsonObject as per your requirements got in onResponse(...).
No comments:
Post a Comment