情况:我有一个API令牌,想要获取json数据。但该标记必须用作标题,而不是查询参数。据我所知,我无法使用标题输入我的浏览器请求。有关我使用的API的更多信息,您可以查看:https://developer.fantasydata.com/docs/services/594407b00f14bf15264fd958/operations/5944088b14338d0eb80b2809
问题:由于我不知道JSON请求有哪些字段,我无法为该json数据创建一个类。我想使用JacksonConverter。所以问题是:如何获得JSON并看看它是什么样的,然后为它创建一个类来转换?
您可以在下面看到我的代码,其中包含可理解的评论:
我的PrefsApplication类用于创建http请求:
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) { }
});
}
}
答案 0 :(得分:2)
您需要向您的Retrofit interceptor
实例添加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 for Retrofit
中详细了解相关信息此示例适用于Retrofit 2+,因此请务必将compile 'com.squareup.retrofit2:retrofit:2.1.0'
添加到您的依赖项中。
答案 1 :(得分:1)
您可以使用浏览器扩展程序并使用自定义标头发出http请求。 I prefer postman for Chrome