Retrofit - 动态传递URL值 - GET方法

时间:2017-08-22 14:55:10

标签: android retrofit2

我有一个网址例如:

https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/KMHDC8AEXAU084769?format=JSON

我想在此动态更改KMHDC8AEXAU084769?format=JSON此部分

如何使用Retrofit2。

我试过了:

@FormUrlEncoded
    @GET("{input}")
    Call<Result> getVin(@Path("input") String input, @Field("format") String format);

@FormUrlEncoded仅支持POST而非GET。

这就是我的称呼方式:

ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

        Call<Result> call = apiService.getVin(vin, "JSON");
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                Result result = response.body();

                Log.e("Result: ", "" + response.body());

                Gson gson = new Gson();
                String json = gson.toJson(result);

                responseTV.setText("" + json);
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                // Log error here since request failed
                Log.e("MainActivity", t.toString());
                Toast.makeText(MainActivity.this, "Try later", Toast.LENGTH_SHORT).show();
            }
        });

2 个答案:

答案 0 :(得分:5)

试试这个:

@GET("/api/vehicles/DecodeVinValues/{input}")
Call<Result> getVin(@Path("input") String input, @Query("format") String format);

@FormUrlEncoded和@Field注释用于POST请求。

@GET注释参数的当前值可能因您使用的baseUrl值而有所不同。

答案 1 :(得分:2)

这在文档中有描述....

  

网址操作

     

可以使用替换块动态更新请求URL   方法参数。替换块是字母数字   由{和}包围的字符串。必须有相应的参数   使用相同的字符串使用@Path注释。

     

也可以添加查询参数。

     

@GET(&#34; group / {id} / users&#34;)来电&gt; groupList(@Path(&#34; id&#34;)int   groupId,@ Query(&#34; sort&#34;)String sort);

     

对于复杂的查询参数   组合可以使用地图。

     

@GET(&#34; group / {id} / users&#34;)来电&gt; groupList(@Path(&#34; id&#34;)int   groupId,@ QueryMap Map options);

对于您想要的网址结构,这应该是这样的:

@GET("{id}")
Call<List<User>> groupList(@Path("id") int id, @Query("format") String format);

http://square.github.io/retrofit/

相关问题