【问题标题】:Retrofit and GET using parameters使用参数进行改造和 GET
【发布时间】:2014-07-28 19:38:25
【问题描述】:

我正在尝试使用 Retrofit 向 Google GeoCode API 发送请求。服务接口如下所示:

public interface FooService {    
    @GET("/maps/api/geocode/json?address={zipcode}&sensor=false")
    void getPositionByZip(@Path("zipcode") int zipcode, Callback<String> cb);
}

当我调用服务时:

OkHttpClient okHttpClient = new OkHttpClient();

RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(Constants.GOOGLE_GEOCODE_URL).setClient(new OkClient(okHttpClient)).build();

FooService service = restAdapter.create(FooService.class);

service.getPositionByZip(zipCode, new Callback<String>() {
    @Override public void success(String jsonResponse, Response response) {
       ...
    }
@Override public void failure(RetrofitError retrofitError) {
    }
});

我收到以下堆栈跟踪:

06-07 13:18:55.337: E/AndroidRuntime(3756): FATAL EXCEPTION: Retrofit-Idle
06-07 13:18:55.337: E/AndroidRuntime(3756): Process: com.marketplacehomes, PID: 3756
06-07 13:18:55.337: E/AndroidRuntime(3756): java.lang.IllegalArgumentException: FooService.getPositionByZip: URL query string "address={zipcode}&sensor=false" must not have replace block.
06-07 13:18:55.337: E/AndroidRuntime(3756):     at retrofit.RestMethodInfo.methodError(RestMethodInfo.java:120)
06-07 13:18:55.337: E/AndroidRuntime(3756):     at retrofit.RestMethodInfo.parsePath(RestMethodInfo.java:216)
06-07 13:18:55.337: E/AndroidRuntime(3756):     at retrofit.RestMethodInfo.parseMethodAnnotations(RestMethodInfo.java:162)
06-07 13:18:55.337: E/AndroidRuntime(3756):     at 

我查看了 StackOverflow 问题:Retrofit: multiple query parameters in @GET command?,但似乎不适用。

我几乎一字不差地从这里获取了代码:http://square.github.io/retrofit/,所以我对理解这个问题有点茫然。

想法?

【问题讨论】:

    标签: android get retrofit


    【解决方案1】:

    AFAIK,{...} 只能用作路径,不能在查询参数中使用。试试这个:

    public interface FooService {    
    
        @GET("/maps/api/geocode/json?sensor=false")
        void getPositionByZip(@Query("address") String address, Callback<String> cb);
    }
    

    如果你有未知数量的参数要传递,你可以这样做:

    public interface FooService {    
    
        @GET("/maps/api/geocode/json")
        @FormUrlEncoded
        void getPositionByZip(@FieldMap Map<String, String> params, Callback<String> cb);
    }
    

    【讨论】:

    • 如何添加多个查询参数
    • @GilbertoIbarra 错误,添加更多内容:void getPositionByZip(@Query("address") String address, @Query("number") String number, Callback&lt;String&gt; cb);
    • FormUrlEncoded 只能在带有请求正文的 HTTP 方法上指定(例如,@POST)
    • 这里回答错误,@FormUrlEncoded 不能与 GET 一起使用
    • @FormUrlEncoded 不适用于 @GET 注释
    【解决方案2】:

    @QueryMap 为我工作,而不是 FieldMap

    如果您有一堆 GET 参数,另一种将它们传递到您的 url 的方法是 HashMap

    class YourActivity extends Activity {
    
    private static final String BASEPATH = "http://www.example.com";
    
    private interface API {
        @GET("/thing")
        void getMyThing(@QueryMap Map<String, String> params, new Callback<String> callback);
    }
    
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.your_layout);
    
       RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();
       API service = rest.create(API.class);
    
       Map<String, String> params = new HashMap<String, String>();
       params.put("key1", "val1");
       params.put("key2", "val2");
       // ... as much as you need.
    
       service.getMyThing(params, new Callback<String>() {
           // ... do some stuff here.
       });
    }
    }
    

    调用的 URL 将是 http://www.example.com/thing/?key1=val1&key2=val2

    【讨论】:

      【解决方案3】:
      @Headers(
          "Accept: application/json",
          "Content-Type: application/json",
          "Platform: android")
      @GET("api/post/post/{id}")
      fun showSelectedPost(
          @Path("id") id: String,
          @Header("Version") apiVersion: Int
      ): Call<Post>
      

      Retrofit + Kotlin + RestAPI 适合我的示例。

      我希望这个带有参数的@Header@GET@Path 也会对某人有所帮助)

      【讨论】:

        【解决方案4】:

        我还想澄清一下,如果要构建复杂的 url 参数,则需要手动构建它们。即如果您的查询是example.com/?latlng=-37,147,您需要在外部构建 latlng 字符串,而不是单独提供 lat 和 lng 值,然后将其作为参数提供,即:

        public interface LocationService {    
            @GET("/example/")
            void getLocation(@Query(value="latlng", encoded=true) String latlng);
        }
        

        注意encoded=true 是必需的,否则改造将编码字符串参数中的逗号。用法:

        String latlng = location.getLatitude() + "," + location.getLongitude();
        service.getLocation(latlng);
        

        【讨论】:

          【解决方案5】:

          Kotlin 中的完整工作示例,我已将我的 API 密钥替换为 1111...

                  val apiService = API.getInstance().retrofit.create(MyApiEndpointInterface::class.java)
                  val params = HashMap<String, String>()
                  params["q"] =  "munich,de"
                  params["APPID"] = "11111111111111111"
          
                  val call = apiService.getWeather(params)
          
                  call.enqueue(object : Callback<WeatherResponse> {
                      override fun onFailure(call: Call<WeatherResponse>?, t: Throwable?) {
                          Log.e("Error:::","Error "+t!!.message)
                      }
          
                      override fun onResponse(call: Call<WeatherResponse>?, response: Response<WeatherResponse>?) {
                          if (response != null && response.isSuccessful && response.body() != null) {
                              Log.e("SUCCESS:::","Response "+ response.body()!!.main.temp)
          
                              temperature.setText(""+ response.body()!!.main.temp)
          
                          }
                      }
          
                  })
          

          【讨论】:

          • 你能把 getWeather(params) 方法定义更清楚吗?
          猜你喜欢
          • 1970-01-01
          • 2016-01-16
          • 2020-06-14
          • 1970-01-01
          • 2018-05-03
          • 2016-07-23
          • 2021-08-28
          • 1970-01-01
          • 2016-01-18
          相关资源
          最近更新 更多