简体   繁体   中英

Retrofit Request with Bearer Token

I'm trying to accomplish a post request attached with Bearer token. When making the call postman I get success.

My interface:

 public interface UserClient {


     // @FormUrlEncoded

     //  @Headers({ "Content-Type: application/json"})

    @POST("todos")


    Call<User>createAccount(

        @Field("id") String id,
        @Field("name") String name

);

In this action, the call is initiated.

    OkHttpClient okHttpClient = new OkHttpClient().newBuilder().addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {



            Request originalRequest = chain.request();

            Request.Builder builder = originalRequest.newBuilder().header("Authorization", "Bearer xxxxxxxxxx"
                    );

            Request newRequest = builder.build();
            return chain.proceed(newRequest);
        }
    }).build();


    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.xx.x:xxxx/")
            .client(okHttpClient)
            .build();


    UserClient client = retrofit.create(UserClient.class);

  //  var k1 = "100000";
    Call<User> call = client.createAccount("777377","ddddddd");

    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            Toast.makeText(MainActivity.this,"Success",Toast.LENGTH_SHORT).show();
            Log.d("RESPONSE",response.toString());
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
            Toast.makeText(MainActivity.this,"Not Success",Toast.LENGTH_SHORT).show();
        }
    });
}

Permissions on manifest have been granted. However on click the application is closed!?

i am sending Bearer token this way :-

Interface class :-

@Headers("Content-Type: application/json")
    @POST("logout")
    Call<LogoutPojo> logOutUser(@Header("Authorization") String token);

or in my activity:-

apiInterface.logOutUser(token)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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