【发布时间】:2017-08-11 10:55:00
【问题描述】:
我正在尝试调用一个需要我传递 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 $
【问题讨论】:
-
为您的改造实例添加一个logging interceptor,因为您的调用参数化错误
-
编译'com.squareup.okhttp3:logging-interceptor:3.0.0'
-
我使用了上面的依赖。任何想法我如何从那里去?
-
@jamian 取决于 okhttp 的版本使用相同的版本
-
@jamian 你试过我的答案吗?
标签: android retrofit httpurlconnection