【问题标题】:How to retrieve JSON using retrofit with headers?如何使用带有标头的改造来检索 JSON?
【发布时间】:2017-12-08 08:07:28
【问题描述】:

情况:我有一个 API 令牌并想获取 json 数据。但是该令牌必须用作标头,而不是查询参数。据我了解,我无法在浏览器请求中输入标题。有关我使用的 API 的更多信息,您可以查看:https://developer.fantasydata.com/docs/services/594407b00f14bf15264fd958/operations/5944088b14338d0eb80b2809

问题:由于我不知道 JSON 请求有什么样的字段,我无法为该 json 数据创建一个类。我想使用 JacksonConverter。所以问题是:如何获取该 JSON 并查看它的外观,然后为其创建一个类以进行转换?

您可以在下面看到我的带有可理解 cmets 的代码:

用于创建 http 请求的 PrefsApplication 类:

public class PrefsApplication extends Application {
    private static Retrofit retrofit = null;

    static String base = "https://api.fantasydata.net/v3/soccer/scores/"; // my base url

    public static Retrofit getClient() {
        if(retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl(base).addConverterFactory(JacksonConverterFactory.create()).build();
        }
        return retrofit;
    }
}

我的获取请求和放置标头的界面

public interface RestInterface {
    @Headers("Ocp-Apim-Subscription-Key: {MY_KEY}") // here is header, I don't know is it properly written?
    @GET("scores/json/Areas") // my get request
    Call<List<Country>> getCountries(); // here, I want to get list of countries
}

有MainActivity:

public class MainActivity extends AppCompatActivity  {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RestInterface rest = PrefsApplication.getClient().create(RestInterface.class);

        Call<List<Country>>call = rest.getCountries();
        call.enqueue(new Callback<List<Country>>() {
            @Override
            public void onResponse(Call<List<Country>> call, Response<List<Country>> response) { }

            @Override
            public void onFailure(Call<List<Country>> call, Throwable t) { }
        });
    }
}

【问题讨论】:

  • “因为我不知道 JSON 请求有哪些类型的字段”——考虑使用具有更好文档的服务。否则,使用该页面上显示的curl 命令获取示例输出。

标签: android json http jackson retrofit


【解决方案1】:

您需要将 interceptor 添加到您的 Retrofit HttpClient 实例。这样您就可以设置自定义标题。

一个简单的例子是:

private static final String API_URL = "URL"; // Override with the service URL
private static final String YOUR_KEY = "KEY"; // Override with your key from the service

private static Retrofit.Builder retrofit = new Retrofit.Builder().baseUrl(API_URL);
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

public static RestInterface endpoint() {
    httpClient.interceptors().clear();

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

            Request.Builder requestBuilder = original.newBuilder()
                    .header("Ocp-Apim-Subscription-Key", YOUR_KEY)
                    .method(original.method(), original.body());

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

    return retrofit.client(httpClient.build()).build().create(RestInterface.class);
}

// Then call to use a Retrofit instance with the headers
PrefsApplication.endpoint().getCountries();

这以各种方式使用,例如添加身份验证。您可以在this complete guide 中阅读更多相关信息以进行改造

此示例适用于 Retrofit 2+,因此请务必将 compile 'com.squareup.retrofit2:retrofit:2.1.0' 添加到您的依赖项中。

【讨论】:

    【解决方案2】:

    您可以使用浏览器扩展并使用自定义标头发出 http 请求。 I prefer postman for Chrome

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-14
      • 2023-03-17
      • 2016-06-21
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多