改造,okhttp3添加标题

时间:2018-05-13 06:17:15

标签: android retrofit okhttp3

我需要从网站上获取XML文件。我正在学习使用Retrofit。 我需要发出请求并通过"X-AppId"标头附加我的API密钥。它应该是这样的:

X-AppId: my key.

如果我从浏览器中执行此操作,我会得到答案。 通过改造,我获得了访问权限

  

错误403禁止代码= 403,消息=禁止,网址= https://

告诉我如何正确实施从服务器code = 200

接收答案

这是我的实施:

public interface myAPIinterface {
@GET("/api/ru/index/route/?from=Minsk&to=Warsaw")
Call<Routes> getProducts();

}

这是我输出到日志的活动:

private void getProducts(){
    final ProgressDialog loading = ProgressDialog.show(this,"Fetching Data","Please wait...",false,false);
    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    Log.d(TAG, "getProducts");
    httpClient.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request()
                    .newBuilder()
                    .addHeader("X-AppId:", "97377f7b702d7198e47a2bf12eec74")
                    .build();
            return chain.proceed(request);
        }
    });

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://rasp.rw.by")
            .addConverterFactory(SimpleXmlConverterFactory.create())
            .build();
    myAPIinterface api = retrofit.create(myAPIinterface.class);
Call<Routes> call = api.getProducts();
    call.enqueue(new Callback<Routes>() {
        @Override
        public void onResponse(@NonNull Call<Routes> call, @NonNull Response<Routes> response) {
            Log.d(TAG, "onResponse");
            Log.d(TAG, String.valueOf(kk));
            Log.d(TAG, String.valueOf(response));
            loading.dismiss();}
       @Override
        public void onFailure(Call<Routes> call, Throwable throwable) {
            loading.dismiss();
            Log.d(TAG, "onFailure" + throwable);
        }
    });

这是一个日志:

  

响应{protocol = http / 1.1,代码= 403,消息=禁止,   URL = https://rasp.rw.by/api/ru/index/route/?from=Minsk&to=Warsaw}

如果我选择没有标题的第三方网站,我会得到200的响应没有问题。在这种情况下我做错了什么?谢谢。

1 个答案:

答案 0 :(得分:0)

哦,伙计,你在做什么。您可以使用@Query,@ Header等注释

public interface myAPIinterface {

    @GET("/api/ru/index/route")
    Call<Routes> getProducts(@Header("X-AppId:") String YOUR_APP_ID,
                             @Query("from") String from,
                             @Query("to") String to)
}

然后你可以创建这样的请求:

Retrofit retrofit = new Retrofit.Builder(). 
.baseUrl("https://rasp.rw.by")
.addConverterFactory(SimpleXmlConverterFactory.create())
.build();

retrofit.create(myAPIinterface.class).getProducts(myId, "Minsk", "Warsaw").enqueue ...

它如何帮助?您忘记在第二次改造时添加标题,然后您有403错误。因此,您必须添加注释,这将是您忘记将值放入标题/查询/等时的最后一个错误。

相关问题