Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit - Pass URL values dynamically - GET method

I have a URL for example :

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

Here I want to change KMHDC8AEXAU084769?format=JSON this part dynamically

How to do it with Retrofit2.

I tried like:

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

But @FormUrlEncoded is only supports for POST not for GET.

This is the way I am calling it:

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();
            }
        });
like image 601
Shailendra Madda Avatar asked Dec 03 '22 21:12

Shailendra Madda


2 Answers

Try this:

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

@FormUrlEncoded and @Field annotations are for POST requests.

Current value of the parameter of @GET annotation may differ according to your baseUrl value you are using.

like image 157
Josef Adamcik Avatar answered Jan 22 '23 01:01

Josef Adamcik


This is described in the documentation....

URL MANIPULATION

A request URL can be updated dynamically using replacement blocks and parameters on the method. A replacement block is an alphanumeric string surrounded by { and }. A corresponding parameter must be annotated with @Path using the same string.

Query parameters can also be added.

@GET("group/{id}/users") Call> groupList(@Path("id") int groupId, @Query("sort") String sort);

For complex query parameter combinations a Map can be used.

@GET("group/{id}/users") Call> groupList(@Path("id") int groupId, @QueryMap Map options);

For your desired url structure this should work with something like this:

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

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

like image 21
Robin Vinzenz Avatar answered Jan 22 '23 02:01

Robin Vinzenz