'how to fix 401 Unauthorized error with using retrofit in android?

I have used retrofit2 library in android. I am getting 401 Unauthorized error. if anyone have solved this issue so please tell me here. I learn retrofit2 use in android. this is APIClient class. APIClient class :

           public class APIClient {
                private static Retrofit retrofit = null;
                private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
                        .connectTimeout(7, TimeUnit.MINUTES)
                        .readTimeout(7, TimeUnit.MINUTES)
                        .writeTimeout(7, TimeUnit.MINUTES)
                        .build();
                public static Retrofit getClient() {
                    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

                    retrofit = new Retrofit.Builder().baseUrl("http://www.example.com/").addConverterFactory(GsonConverterFactory.create())
                            .client(okHttpClient).build();

                    return retrofit;
                }
            }

this is my interface.

                    public interface APIInterface {
                        @GET("/teacher/api/getStudentTakeAttendanceList")
                        Call<List<Apiresponse>> getstudentAttendanceListView(@Query("teacherId") int userId);

                    //    Callback<List<Apiresponse>> studentAttendanceListView(@Query("teacherId") int userId);
                    }         

this is my final call.

final Call<List<Apiresponse>> getstudentAttendanceListView = apiInterface.getstudentAttendanceListView(userId);
            getstudentAttendanceListView.enqueue(new Callback<List<Apiresponse>>() {
                    @Override
                    public void onResponse(Call<List<Apiresponse>> call, Response<List<Apiresponse>> response) {
                        Log.d("responsecode:::", "" + response.code());

                        if (progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        Log.e("response::", "" + response.errorBody());

    //                    Log.e("response::", "" + response.body());

                    }

                    @Override
                    public void onFailure(Call<List<Apiresponse>> call, Throwable t) {
                        call.cancel();
                        if (progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                    }
                });
in app.gradle file.
        compile 'com.squareup.retrofit2:retrofit:2.0.2'
        compile 'com.squareup.retrofit2:converter-gson:2.0.2'
    output.
    responsecode:::: 401
    response::: okhttp3.ResponseBody$1@537beb4c


Solution 1:[1]

A 401 Unauthorized error means that you don't have the rights to access. In your case it means that you have to add a header with a accessToken.

Here is explained how to do this.

Solution 2:[2]

you should add your api access token in the request header, you should ask your api developer for the headers keys,you should also try the request first with postman

Solution 3:[3]

Issue can be in yours Headers. "Authorization: Basic TUM6TUMxIU1D" solved my problem.

@Headers("Authorization: Basic TUM6TUMxIU1D")
@GET("nomenclature")
fun getNomenclature(@Query("access_token") accessToken: String): Single<Response>

Solution 4:[4]

401 Unauthorized Retrofit It means you don't have the rights to access.

private fun getTestData() {

        val client =  OkHttpClient.Builder()
            .addInterceptor(BasicAuthInterceptor("username","paswword"))
            .build()
        val gson = GsonBuilder()
            .setLenient()
            .create();
         val api = Retrofit.Builder()
            .baseUrl(Baseurl)
      
      //use this
            .client(client)
      //to solve the problem
      
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
            .create(ApiInterface::class.java)
        api.getData().enqueue(object : Callback<Mytest?> {
            override fun onResponse(call: Call<Mytest?>?, response: Response<Mytest?>?) {
                //TODO("Not yet implemented")
                val responseBody= response?.body()

                val stringBuilder=StringBuilder()

                stringBuilder.append(responseBody?.id)

        
                        Log.v("testjee",responseBody.toString())

            }

            override fun onFailure(call: Call<Mytest?>?, t: Throwable?) {
                //TODO("Not yet implemented")
                showInfo.toastShort("error"+ t?.message.toString())
                Log.d("error",t.toString())
                if (t != null) {
                    print("testjee"+t.message.toString())
                }
            }
        })

    }

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Headers

interface ApiInterface {


    @GET("xxx/xxx")
    fun getData(): Call<Mytest>
}

implementation 'com.squareup.okhttp3:logging-interceptor:3.12.0'
    //implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'

    implementation 'com.squareup.okhttp3:okhttp-ws:3.4.1'

    implementation "com.squareup.okhttp3:okhttp-urlconnection:3.4.1"

    implementation 'com.squareup.retrofit2:retrofit:2.1.0'
    implementation 'com.squareup.retrofit2:converter-jackson:2.1.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.2.0'


    configurations.all {
        // OkHttp 3.5.0+ includes the websockets API, so we need this to prevent a conflict
        //exclude module: 'okhttp-ws'
        resolutionStrategy.force 'com.squareup.okhttp3:okhttp:3.4.1'
    }
import okhttp3.Credentials
import okhttp3.Interceptor


class BasicAuthInterceptor(username: String, password: String): Interceptor {
    private var credentials: String = Credentials.basic(username, password)

    override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
        var request = chain.request()
        request = request.newBuilder().header("Authorization", credentials).build()
        return chain.proceed(request)
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lukas
Solution 2 Reham Alatris
Solution 3 Вадим Гарань
Solution 4 Jeeva Ikk