如何在改造2.0中添加动态标题

时间:2017-09-08 06:13:51

标签: android retrofit2

我正在尝试添加网络请求的动态标头。但它有像 NullPointer 这样的错误。我试过这种方式。

public interface ApiInterface {

@Multipart
@POST("/api/v1/me")
Call<LoginResponse> completeProfile(@Header("Accept") String accept, @Header("Authorization") String token,
       @Part("username") RequestBody username, @Part("full_name") RequestBody full_name, @Part("email") RequestBody email);
}

在我这样称呼之后,我没有得到任何回应的值。有时我得到错误。我把我对邮递员的成功要求作为图片附上。可以指导我错过的地方。

try {

            ApplicationData.hideKeyboard(activity);
            showProgressDialog();
            RequestBody _name = RequestBody.create(MediaType.parse("text/plain"), name);
            RequestBody _user_name = RequestBody.create(MediaType.parse("text/plain"), user_name);
            RequestBody _email = RequestBody.create(MediaType.parse("text/plain"), email);
            RequestBody _home_town = RequestBody.create(MediaType.parse("text/plain"), home_town);
            RequestBody _date_of_birth = RequestBody.create(MediaType.parse("text/plain"), date_of_birth);

            ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
            Call<LoginResponse> call = apiService.completeProfile(ApplicationData.ACCEPT, ApplicationData.AUTHORIZE +
                    "" + ApplicationData.token, _user_name, _name, _email, _home_town, _date_of_birth);
            call.enqueue(new Callback<LoginResponse>() {
                @Override
                public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {

                    hideProgressDialog();
                    LoginResponse loginResponse = response.body();

                    // got crash here null pointer
//                    LogMe.e("response",":"+loginResponse.getMessage());
                    goToHomeActivity();


                }

                @Override
                public void onFailure(Call<LoginResponse> call, Throwable t) {

                    LogMe.e(TAG, t.getMessage());
                    hideProgressDialog();
//
                }
            });

        } catch (Exception e) {

            e.getMessage();
            e.printStackTrace();

        }

邮差:与图片enter image description here中的这些数据一起反应良好 的更新 邮递员的身体部位  enter image description here

2 个答案:

答案 0 :(得分:0)

请试试这个。

Call<LoginResponse> completeProfile(@Header("Accept") String accept, @Header("Authorization") String token,
   @Part("username") RequestBody username, @Part("full_name") RequestBody full_name, @Part("email") RequestBody email);
}

Call<LoginResponse> call = apiService.completeProfile(ApplicationData.ACCEPT, ApplicationData.token, _user_name, _name, _email, _home_town, _date_of_birth);

答案 1 :(得分:0)

此博客文章展示了如何向您的Retrofit请求添加动态数量的请求标头。

这是Retrofit 2.1的新功能,因此请确保在试用之前更新了应用。

Dynamic Request Headers with @HeaderMap