我正在尝试调用一个需要我传递 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 进入 Success,因为我显然需要在某处传递 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 $
原文由 jamian 发布,翻译遵循 CC BY-SA 4.0 许可协议
在尝试了几次之后,我想出了答案。
错误
由于解析 json 失败。
在方法调用中,我传递的是 String 而不是 POJO 类。
我应该通过 Call< Data > 的类型而不是 Call< String >
数据是 Pojo 类
像这样的东西