这是我的界面:

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键?

最佳答案

只需将查询添加以逗号分隔

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);

关于android - 改造2用api键发布?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43859927/

10-08 23:35