在 Retrofit 中添加 Header 参数
Add Header Parameter in Retrofit
我正在尝试调用 API,这需要我传递 API 密钥。
我使用 HttpURLConnection
的服务调用工作正常。
url = new URL("https://developers.zomato.com/api/v2.1/search?entity_id=3&entity_type=city&q=" + params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("user-key","9900a9720d31dfd5fdb4352700c");
if (urlConnection.getResponseCode() != 200) {
Toast.makeText(con, "url connection response not 200 | " + urlConnection.getResponseCode(), Toast.LENGTH_SHORT).show();
Log.d("jamian", "url connection response not 200 | " + urlConnection.getResponseCode());
throw new RuntimeException("Failed : HTTP error code : " + urlConnection.getResponseCode());
}
但是,我不确定这是如何与 Retrofit
一起工作的,因为我一直呼吁进入失败状态。
这是我用于同一服务调用的代码
@GET("search")
Call<String> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query,@Header("Accept") String accept, @Header("user-key") String userkey);
我用这个来称呼它
Call<String> call = endpoint.getRestaurantsBySearch("3","city","mumbai","application/json","9900a9720d31dfd5fdb4352700c");
所有这些调用都将进入 RetroFit 中的 OnFailure
方法。
如果我在没有 HeaderParameters 的情况下发送它,它会以 403 进入成功状态,因为我显然需要在某处传递 api 键,但我不知道如何传递。
@GET("search")
Call<String> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query);
我在 OnFailure 中遇到的错误是
java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2 path $
据我所知,您传递数据的方式有误。
您的方法 getRestaurantsBySearch
接受最后两个参数作为 header 字段,即 accept
和 user-key
。但是在调用该方法时,您首先要传递 headers。
传递您在 getRestaurantsBySearch
的方法签名中声明的数据
您可以使用下面的
@Headers("user-key: 9900a9720d31dfd5fdb4352700c")
@GET("api/v2.1/search")
Call<String> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query);
和
Call<String> call = endpoint.getRestaurantsBySearch("3","city","cafes");
以上内容基于 zomato api,记录在
https://developers.zomato.com/documentation#!/restaurant/search
需要注意的是终点变化api/v2.1/search和Header@Headers("user-key: 9900a9720d31dfd5fdb4352700c")
.
同时检查你的基地 url .baseUrl("https://developers.zomato.com/")
我还用我生成的 api 密钥尝试了上面的方法并且它有效
根据 zomato 文档的建议,我的查询是 cafes。
注意:希望您有以下内容
.addConverterFactory(ScalarsConverterFactory.create()) // for string conversion
.build();
以及 build.gradle 文件中的以下内容
compile group: 'com.squareup.retrofit2', name: 'converter-scalars', version: '2.2.0'
编辑:
你也可以传递 header 动态值如下
@GET("api/v2.1/search")
Call<String> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query,@Header("user-key") String userkey);
和
Call<String> call = endpoint.getRestaurantsBySearch("3","city","cafes","9900a9720d31dfd5fdb4352700c");
请看一下回复。它清楚地表明您提供的 api 密钥是错误的。首先你得到正确的 api 键。然后调用它会起作用的请求
.
尝试了几次后我找到了答案。
错误
java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2 path $
由于解析 json 失败而即将到来。
在方法调用中,我传递的是字符串而不是 POJO class。
@Headers("user-key: 9900a9720d31dfd5fdb4352700c")
@GET("api/v2.1/search")
Call<String> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query);
我应该传递 Call<String> 而不是 Call<Data>
的类型
数据是 Pojo class
像这样
@Headers("user-key: 9900a9720d31dfd5fdb4352700c")
@GET("api/v2.1/search")
Call<Data> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query);
为 Retrofit 1.9 和 2.0 尝试这种类型 header。对于 JSON 内容类型。
@Headers({"Accept: application/json"})
@POST("user/classes")
Call<playlist> addToPlaylist(@Body PlaylistParm parm);
您可以添加更多 header,即
@Headers({
"Accept: application/json",
"User-Agent: Your-App-Name",
"Cache-Control: max-age=640000"
})
动态地添加到headers:
@POST("user/classes")
Call<ResponseModel> addToPlaylist(@Header("Content-Type") String content_type, @Body RequestModel req);
调用您的方法,即
mAPI.addToPlayList("application/json", playListParam);
或
想每次都通过,那么创建一个带有HTTP拦截器的HttpClientobject:
OkHttpClient httpClient = new OkHttpClient();
httpClient.networkInterceptors().add(new Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
Request.Builder requestBuilder = chain.request().newBuilder();
requestBuilder.header("Content-Type", "application/json");
return chain.proceed(requestBuilder.build());
}
});
然后添加到 Retrofit object
Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(httpClient).build();
如果您使用的是 Kotlin,请删除 { }
。否则不行。
我正在尝试调用 API,这需要我传递 API 密钥。
我使用 HttpURLConnection
的服务调用工作正常。
url = new URL("https://developers.zomato.com/api/v2.1/search?entity_id=3&entity_type=city&q=" + params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("user-key","9900a9720d31dfd5fdb4352700c");
if (urlConnection.getResponseCode() != 200) {
Toast.makeText(con, "url connection response not 200 | " + urlConnection.getResponseCode(), Toast.LENGTH_SHORT).show();
Log.d("jamian", "url connection response not 200 | " + urlConnection.getResponseCode());
throw new RuntimeException("Failed : HTTP error code : " + urlConnection.getResponseCode());
}
但是,我不确定这是如何与 Retrofit
一起工作的,因为我一直呼吁进入失败状态。
这是我用于同一服务调用的代码
@GET("search")
Call<String> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query,@Header("Accept") String accept, @Header("user-key") String userkey);
我用这个来称呼它
Call<String> call = endpoint.getRestaurantsBySearch("3","city","mumbai","application/json","9900a9720d31dfd5fdb4352700c");
所有这些调用都将进入 RetroFit 中的 OnFailure
方法。
如果我在没有 HeaderParameters 的情况下发送它,它会以 403 进入成功状态,因为我显然需要在某处传递 api 键,但我不知道如何传递。
@GET("search")
Call<String> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query);
我在 OnFailure 中遇到的错误是
java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2 path $
据我所知,您传递数据的方式有误。
您的方法 getRestaurantsBySearch
接受最后两个参数作为 header 字段,即 accept
和 user-key
。但是在调用该方法时,您首先要传递 headers。
传递您在 getRestaurantsBySearch
您可以使用下面的
@Headers("user-key: 9900a9720d31dfd5fdb4352700c")
@GET("api/v2.1/search")
Call<String> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query);
和
Call<String> call = endpoint.getRestaurantsBySearch("3","city","cafes");
以上内容基于 zomato api,记录在
https://developers.zomato.com/documentation#!/restaurant/search
需要注意的是终点变化api/v2.1/search和Header@Headers("user-key: 9900a9720d31dfd5fdb4352700c")
.
同时检查你的基地 url .baseUrl("https://developers.zomato.com/")
我还用我生成的 api 密钥尝试了上面的方法并且它有效 根据 zomato 文档的建议,我的查询是 cafes。
注意:希望您有以下内容
.addConverterFactory(ScalarsConverterFactory.create()) // for string conversion
.build();
以及 build.gradle 文件中的以下内容
compile group: 'com.squareup.retrofit2', name: 'converter-scalars', version: '2.2.0'
编辑:
你也可以传递 header 动态值如下
@GET("api/v2.1/search")
Call<String> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query,@Header("user-key") String userkey);
和
Call<String> call = endpoint.getRestaurantsBySearch("3","city","cafes","9900a9720d31dfd5fdb4352700c");
请看一下回复。它清楚地表明您提供的 api 密钥是错误的。首先你得到正确的 api 键。然后调用它会起作用的请求 .
尝试了几次后我找到了答案。
错误
java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2 path $
由于解析 json 失败而即将到来。
在方法调用中,我传递的是字符串而不是 POJO class。
@Headers("user-key: 9900a9720d31dfd5fdb4352700c")
@GET("api/v2.1/search")
Call<String> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query);
我应该传递 Call<String> 而不是 Call<Data>
的类型数据是 Pojo class
像这样
@Headers("user-key: 9900a9720d31dfd5fdb4352700c")
@GET("api/v2.1/search")
Call<Data> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query);
为 Retrofit 1.9 和 2.0 尝试这种类型 header。对于 JSON 内容类型。
@Headers({"Accept: application/json"})
@POST("user/classes")
Call<playlist> addToPlaylist(@Body PlaylistParm parm);
您可以添加更多 header,即
@Headers({
"Accept: application/json",
"User-Agent: Your-App-Name",
"Cache-Control: max-age=640000"
})
动态地添加到headers:
@POST("user/classes")
Call<ResponseModel> addToPlaylist(@Header("Content-Type") String content_type, @Body RequestModel req);
调用您的方法,即
mAPI.addToPlayList("application/json", playListParam);
或
想每次都通过,那么创建一个带有HTTP拦截器的HttpClientobject:
OkHttpClient httpClient = new OkHttpClient();
httpClient.networkInterceptors().add(new Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
Request.Builder requestBuilder = chain.request().newBuilder();
requestBuilder.header("Content-Type", "application/json");
return chain.proceed(requestBuilder.build());
}
});
然后添加到 Retrofit object
Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(httpClient).build();
如果您使用的是 Kotlin,请删除 { }
。否则不行。