如何将标题中的令牌发送到Android中的服务器

时间:2017-09-19 06:21:10

标签: android retrofit retrofit2

在我的应用程序中,我想创建一个登录 / 注册页面。

在登录页面中,我将用户名密码令牌从客户端发送到服务器。

我应该从 USER 获取用户名密码,并从HEADER获取令牌请求。

对于将客户端连接到服务器,我使用Retorfit 2.2.0库。

Interface类的代码:

@POST("User/Authenticate")
Call<LoginResponse> getLoginResponse(@Header("Token") String token, @Body LoginDatum loginDatum);

活动中的代码:

public void getLogin(String username, String password) {

    final LoginDatum loginDatum = new LoginDatum();
    loginDatum.setUsername(username);
    loginDatum.setPassword(password);

    InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
    Call<LoginResponse> call = api.getLoginResponse(sendToken, loginDatum);

    Log.e("tokenTAG", "Token : " + sendToken);

    call.enqueue(new Callback<LoginResponse>() {
        @Override
        public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
            LoginResponse loginResponse = response.body();
            String token = response.headers().get("Token");
            if (token != null) {
                sendToken = token;
                Log.e("tokenTAG", "Token : " + sendToken);
            }
            if (loginResponse.getStatusCode() == 200) {
                Toasty.success(context, context.getResources().getString(R.string.welcome) + " " +
                        loginResponse.getData().getName(), Toast.LENGTH_LONG, true).show();
            } else {
                Toasty.error(context, loginResponse.getStatusMessage() + "", Toast.LENGTH_LONG, true).show();
            }
            loadProgress.get(0).setVisibility(View.GONE);
            loginBtn.setVisibility(View.VISIBLE);
            btnShadow.setVisibility(View.VISIBLE);
        }

        @Override
        public void onFailure(Call<LoginResponse> call, Throwable t) {
            loadProgress.get(0).setVisibility(View.GONE);
            loginBtn.setVisibility(View.VISIBLE);
            btnShadow.setVisibility(View.VISIBLE);
            Toasty.error(context, context.getResources().getString(R.string.failRequest),
                    Toast.LENGTH_LONG, true).show();
        }
    });
}

在LogCat中向我展示:

tokenTAG: Token : null
tokenTAG: Token : MKGKFPOVRMU4MRK0STNDO20RA2MPEWT7Y1N2WUM5QLIXJX2TEOM9APGUTYJMD8R42WFVESD8GRXCTCINA2LZKU7JV2I7KA2R4N5W

但是,当我想使用此代码发送令牌时:Call<LoginResponse> call = api.getLoginResponse(sendToken, loginDatum);它会显示 null

我已使用此行:Call<LoginResponse> call = api.getLoginResponse(sendToken, loginDatum);生成请求callBack,但此行令牌不是NUll

我该如何解决?

2 个答案:

答案 0 :(得分:0)

如果您使用Retrifit get onNetwork请求,为了将Header添加到您的requese,您必须编写Intercepter。

答案 1 :(得分:-1)

用这个替换getClient menthod

  public static Retrofit getClient(final Context context) {
        if (retrofit == null) {
            Log.d("AuthTokenTest", "getClient: null");

            OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

            dispatcher = new Dispatcher();
            httpClient.dispatcher(dispatcher);

            httpClient.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Interceptor.Chain chain) throws IOException {
                    Request original = chain.request();
                    Log.d("INTERCEPTOR", original.url().toString());
                    //System.out.print(original.toString());
                    Request request;
                    user=User.getLoggedInUserInstance(context);
                    String authToken="";

                    if(user!=null)
                        authToken=user.getAuthToken();
                    Log.d("AuthTokenTest", "intercept: authtoken:"+authToken);

                    request = original.newBuilder()
                            .header("X-AUTH-TOKEN", authToken)
                            .header("x-requested-with", "XMLHttpRequest")
                            .method(original.method(), original.body())
                            .build();

                    okhttp3.Response response = chain.proceed(request);

                    Log.d("INTERCEPTOR-", "response_code: "+response.code());

//                    Log.d("INTERCEPTOR", response.body().string());
                    return response;

                }
            });

            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            if(BuildConfig.DEBUG){
                //print the logs in this case
                loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            }else{
                loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
            }

            httpClient.addInterceptor(loggingInterceptor);

            OkHttpClient client = httpClient.build();

            Gson gson = new GsonBuilder()
                    .excludeFieldsWithModifiers(Modifier.TRANSIENT)
                    .setLenient()
                    .create();

            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return retrofit;
    }

让我知道此解决方案是否有效