如何在Retrofit 2.1.0中传递Header

时间:2016-12-22 06:41:11

标签: java android retrofit

嗨从最后两个我坚持这个改造任何人请帮助我。我已经尝试了很多方法来通过改造中的标题可以但我不能使用Retrofit 2.0.1

的build.gradle

compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
compile 'com.squareup.okhttp:okhttp:2.7.2'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

并且在 ApiClientHeader.jav

        import okhttp3.Interceptor;
        import okhttp3.OkHttpClient;
        import okhttp3.Request;
        import okhttp3.Response;
        import retrofit2.Retrofit;
        import retrofit2.converter.gson.GsonConverterFactory;

        public class ApiClientHeader {

        public static final String BASE_URL = "URL";
        private static Retrofit retrofit = null;


        public static Retrofit getClient(final String token) {


            OkHttpClient okClient = new OkHttpClient.Builder()
                    .addInterceptor(
                            new Interceptor() {
                                @Override
                                public Response intercept(Interceptor.Chain chain) throws IOException {
                                    Request original = chain.request();

                                    // Request customization: add request headers
                                    Request.Builder requestBuilder = original.newBuilder()
                                            .header("Authorization", "Bearer " + token)
                                            .method(original.method(), original.body());

                                    Request request = requestBuilder.build();
                                    return chain.proceed(request);
                                }
                            })
                    .build();


            if (retrofit == null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .client(okClient)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }

    }

而在我的 ApiInterface.java

@GET("profile")
Call<JsonObject> getProfile();

在我的活动中,我只是在调用函数

    private void getProfileData()
    {
        Singleton single = new Singleton();
        String auth = single.getAuthorization();

        Log.d("===========>>>>>>",auth);


        ApiInterface apiService =
                ApiClientHeader.getClient(auth).create(ApiInterface.class);
        //showProgress(true);
        Call<JsonObject> profileResponse = apiService.getProfile();
        profileResponse.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {

                //showProgress(false);

                Log.d("============>"," Call Request " +String.valueOf(call.request().toString()));
                Log.d("============>", " Response code " + String.valueOf(response.code()));
//                Log.d("============>", " Response Body " + String.valueOf(response.body().toString()));

                if(response.code() == HttpURLConnection.HTTP_OK)
                {

                }

            }

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

                //showProgress(false);
                Log.d("============>"," Call Request " +String.valueOf(call.request().toString()));
                Log.d("============>"," Call Request " +String.valueOf(call.request().headers()));
                Log.d("=======>", "Failure" + t.getMessage());
            }

        });
    }

我仍然得到403无效的访问权限。 在这里,我没有使用任何POJO类来发送或接收数据。请帮帮我。

4 个答案:

答案 0 :(得分:1)

您必须像这样传递您的身份验证字符串

@GET("profile")
Call<JsonObject> getProfile((@Header("Authorization") String authorization))

答案 1 :(得分:0)

    @Headers({
    "Accept: application/vnd.github.v3.full+json",
    "User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);

documentation

的更多信息

答案 2 :(得分:0)

我找到了Token based authentication using Retrofit 1.9 + OkHttp 2.4

的最佳链接之一

您可以添加NetworkInterceptor,我在我的演示中使用过它,如:

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

依赖关系:

stdlib1.jar

谢谢。

答案 3 :(得分:-1)

在您的课程中尝试以下代码,这对我有用:

final RestAdapter restAdapter = new RestAdapter.Builder().setClient(client).setLogLevel(RestAdapter.LogLevel.FULL).setRequestInterceptor(new RequestInterceptor() {

            @Override
            public void intercept(RequestFacade requestFacade) {
                requestFacade.addHeader("key", "value");
                requestFacade.addHeader("X-Requested-With", "XMLHttpRequest");
            }
        }).setConverter(new GsonConverter(gson)).setEndpoint(context.getString(R.string.base_url)).build();

编辑帖子:

public class RestClient {

    // private static final String BASE_URL = "http://api.plumperfect.com";
    private WebServicesInterface apiService;
    private static RestClient instance;

    public RestClient(Context context) {
        instance = this;
        final Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ItemTypeAdapterFactory()).setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'").create();
        // final int cacheSize = 10 * 1024 * 1024; // 10 MiB
        // final File cacheDirectory = new File(context.getCacheDir().getAbsolutePath(), "HttpCache");
        // final OkHttpClient client = new OkHttpClient();
        // Cache cache;
        // try {
        // cache = new Cache(cacheDirectory, cacheSize);
        // client.setCache(cache);
        // } catch (IOException e) {
        // e.printStackTrace();
        // }


        final OkHttpClient okHttpClient = new OkHttpClient();

        final Client client = new OkClient(okHttpClient);

        final RestAdapter restAdapter = new RestAdapter.Builder().setClient(client).setLogLevel(RestAdapter.LogLevel.FULL).setRequestInterceptor(new RequestInterceptor() {

            @Override
            public void intercept(RequestFacade requestFacade) {
                      requestFacade.addHeader("key", "value");
                requestFacade.addHeader("X-Requested-With", "XMLHttpRequest");
            }
        }).setConverter(new GsonConverter(gson)).setEndpoint(context.getString(R.string.base_url)).build();

        apiService = restAdapter.create(WebServicesInterface.class);
    }

    public WebServicesInterface getApiService() {
        return apiService;
    }

    public static RestClient getInstance() {
        return instance;
    }

}

Secound Class:

public class ItemTypeAdapterFactory implements TypeAdapterFactory {

    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
        final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

        return new TypeAdapter<T>() {

            public void write(JsonWriter out, T value) throws IOException {
                delegate.write(out, value);
            }

            public T read(JsonReader in) throws IOException {

                JsonElement jsonElement = elementAdapter.read(in);
                if (jsonElement.isJsonObject()) {
                    JsonObject jsonObject = jsonElement.getAsJsonObject();
                    if (jsonObject.has(Constants.DATA) && jsonObject.get(Constants.DATA).isJsonObject()) {
                        jsonElement = jsonObject.get(Constants.DATA);
                    }
                }

                return delegate.fromJsonTree(jsonElement);
            }
        }.nullSafe();
    }

}