【发布时间】: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