简体   繁体   English

如何在 android 中使用改造来修复 401 Unauthorized 错误?

[英]how to fix 401 Unauthorized error with using retrofit in android?

I have used retrofit2 library in android.我在android中使用了retrofit2库。 I am getting 401 Unauthorized error.我收到 401 未经授权的错误。 if anyone have solved this issue so please tell me here.如果有人解决了这个问题,请在这里告诉我。 I learn retrofit2 use in android.我在android中学习retrofit2的使用。 this is APIClient class.这是 APIClient 类。 APIClient class : APIClient 类:

           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

A 401 Unauthorized error means that you don't have the rights to access. 401 Unauthorized error意味着您没有访问权限。 In your case it means that you have to add a header with a accessToken.在您的情况下,这意味着您必须添加带有 accessToken 的标头。

Here is explained how to do this. 这里解释了如何做到这一点。

您应该在请求标头中添加您的 api 访问令牌,您应该向您的 api 开发人员询问标头密钥,您还应该首先使用邮递员尝试请求

Issue can be in yours Headers.问题可以在您的标题中。 "Authorization: Basic TUM6TUMxIU1D" solved my problem. “授权:基本 TUM6TUMxIU1D”解决了我的问题。

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

401 Unauthorized Retrofit It means you don't have the rights to access. 401 Unauthorized Retrofit表示您没有访问权限。

 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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM