简体   繁体   中英

How to Call this webservice in Retrofit

How can I call the following service endpoint in a RESTful web service in Retrofit2?

My service endpoint:

http://crb.cloud/mileage/api/?expanse_view_user&Appkey=MiLeAgE&Userid=1&Vehid=1

My code:

interface APIInterface {
@GET("expanse_view_user/{Appkey}")
Call<Example> getUserById(@Path("Appkey") String mlg, @Query("Userid") 
    Integer id , @Query("Vehid") Integer vehid);

}


class APIClient {
private static Retrofit retrofit = null;
static Retrofit getClient() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

    retrofit = new Retrofit.Builder()
            .baseUrl("http://crb.cloud/mileage/api/?")
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();
    //expanse_view_user&Appkey=MiLeAgE&Userid=1&Vehid=17
    return retrofit;
}
}


public class MainActivity extends AppCompatActivity {

APIInterface apiInterface;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    apiInterface = APIClient.getClient().create(APIInterface.class);
    Call<Example> call = apiInterface.getUserById("MiLeAgE",1,17);
    call.enqueue(new Callback<Example>() {
        @Override
        public void onResponse(Call<Example> call, Response<Example> response) {
            Log.e("TAG",response.code()+"");

            String displayResponse = "";

            Example resource = response.body();
            Integer text = resource.status;
            String total = resource.message;
            }
        }
        @Override
        public void onFailure(Call<Example> call, Throwable t) {
        }
    }); 
}
}

You can use HashMap . For example:

@GET("?expanse_view_user")
Call<YourModelClass> getUserById(@QueryMap HashMap<String, String> params);

From where you are requesting to the server, you can use like this:

HashMap<String, String> params = new HashMap<>();
params.put("key1", "value1");
params.put("key2", "value2");
params.put("key3", "value3");

apiInterface = APIClient.getClient().create(APIInterface.class);
Call<Example> call = apiInterface.getUserById(params);

You can create your api like this

@GET("?expanse_view_user")
Call<Example> getData(@Query("Appkey") String Appkey, @Query("Userid") String Userid, @Query("Vehid") String Vehid);

and the base url as http://crb.cloud/mileage/api/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM