改造2使用apikey发布?

时间:2017-05-09 02:10:16

标签: android retrofit retrofit2

这是我的界面:

public interface ApiInterface {
@GET("solicitation/all")
Call<SolicitationResponse> getAllNews(@Query("X-Authorization") String apiKey);

@POST("solicitation/create ")
Call<Solicitation> createSolicitation(@Body Solicitation solicitation);
}

这是创建新请求的MainActivity代码:

    Solicitation solicitation = new Solicitation("xx", "list", "31", "32", "description goes here", "file goes here", "userid goes here", "203120312");

    ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

    Call<Solicitation> call = apiService.createSolicitation(solicitation);
    call.enqueue(new Callback<Solicitation>() {
        @Override
        public void onResponse(Call<Solicitation> call, Response<Solicitation> response) {
            Log.d("Response::", "Success!");
        }

        @Override
        public void onFailure(Call<Solicitation> call, Throwable t) {
            Log.e("Response::", "Fail!!");
        }
    });

问题是,正如您在查询中看到的那样,我使用api密钥。 @Query("X-Authorization")

似乎我不能对@Body做同样的事。

有没有办法在查询中插入api密钥?

1 个答案:

答案 0 :(得分:4)

只需用逗号

分隔查询
Call<Solicitation> createSolicitation(@Query("X-Authorization") String apiKey, @Body Solicitation solicitation);

或标题

Call<Solicitation> createSolicitation(@Header("X-Authorization") String apiKey, @Body Solicitation solicitation);

或者你需要一个拦截器来插入标题

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();  
httpClient.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("X-Authorization", "YOUR AUTH KEY"); // <-- this is the important line

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

OkHttpClient client = httpClient.build();  

使用

Call<Solicitation> call = apiService.createSolicitation("YOUR API KEY",solicitation);