How to call the API in Android(Retrofit)
//Main Class
//Main Class
import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Toast import com.example.demoapicall.network.ApiInterface import com.example.demoapicall.network.ServiceClient import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_main.* import org.json.JSONObject import retrofit2.HttpException class MainActivity : AppCompatActivity() { private var mCompositeDisposable: CompositeDisposable? = null
private var apiService: ApiInterface? = null
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Init
init() //Gett Data btnGetData.setOnClickListener {
getData() } } private fun getData() { mCompositeDisposable?.add( apiService!!.updateProfile( "7 ", "435", "6", "7", "6", "7" ) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(this::handleResponse, this::handleError) ) } private fun init() { apiService = ServiceClient().getClientHeader("your token") .create(ApiInterface::class.java) mCompositeDisposable = CompositeDisposable() } //Getting the Response Here
private fun handleResponse(loginResponse: LoginResponse) { if (loginResponse.status == 200) { Toast.makeText(this, loginResponse.message, Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, loginResponse.message, Toast.LENGTH_SHORT).show() } } private fun handleError(error: Throwable) { Log.i("", "handleError: $error") Log.i("", "handleError: $error") if (error is HttpException) { val errorBody = error.response().errorBody()!!.string(); val jsonObject = JSONObject(errorBody) if (jsonObject.optInt("status") == 203) { } else if (jsonObject.optInt("status") == 205) { } else if (jsonObject.optInt("status") == 201) { } else { Toast.makeText(this, "Authentication Failed", Toast.LENGTH_SHORT).show() } } } }
//Api Interface import com.example.demoapicall.LoginResponse import io.reactivex.Observable import okhttp3.RequestBody import retrofit2.Call import retrofit2.http.* import retrofit2.http.Multipartimport retrofit2.http.POST interface ApiInterface { @FormUrlEncoded @POST("api / your end url") fun updateProfile( @Field("parameter 1") user_id: String, @Field("parameter 2") about: String, @Field("parameter 3") course: String, @Field("parameter 4") year_of_study: String, @Field("parameter 5") gender: String, ): Observable<Your Model> }
//Service client import okhttp3.ConnectionSpec import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.util.* import java.util.concurrent.TimeUnit public class ServiceClient { private lateinit var interceptor: HttpLoggingInterceptor private lateinit var okHttpClient: OkHttpClient private var retrofit: Retrofit? = null
//For with out token val client: Retrofit get() { interceptor = HttpLoggingInterceptor() interceptor.level = HttpLoggingInterceptor.Level.BODY
okHttpClient = OkHttpClient.Builder() .addInterceptor(interceptor) .connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS)) .followRedirects(true) .followSslRedirects(true) .retryOnConnectionFailure(true) .connectTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .cache(null) .build() if (retrofit == null) { retrofit = Retrofit.Builder() .baseUrl("your base url") .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build() } return retrofit!! } //For require token fun getClientHeader(header: String): Retrofit { val httpLoggingInterceptor = HttpLoggingInterceptor() httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY) val httpClient = OkHttpClient.Builder() httpClient.addInterceptor { chain ->
val original = chain.request() val request = original.newBuilder() .header("Authorization", header) .method(original.method(), original.body()) .build() chain.proceed(request) } httpClient.interceptors().add(httpLoggingInterceptor) httpClient.readTimeout(120, TimeUnit.SECONDS) httpClient.connectTimeout(120, TimeUnit.SECONDS) val client = httpClient.build() retrofit = Retrofit.Builder() .baseUrl("your base url") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(client) .build() return retrofit!! } }
//Need to add libary in Gradle
implementation 'com.squareup.retrofit2:adapter-rxjava:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
implementation "com.squareup.retrofit2:retrofit:2.0.0"
implementation "com.squareup.retrofit2:converter-gson:2.0.0"
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'io.reactivex.rxjava2:rxjava:2.1.6'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
No comments:
Post a Comment