如何在Retrofit中调用此Web服务

时间:2017-07-26 12:04:08

标签: android web-services retrofit

如何在Retrofit2中的RESTful Web服务中调用以下服务端点?

我的服务终端:

  

this demo

我的代码:

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) {
        }
    }); 
}
}

2 个答案:

答案 0 :(得分:0)

您可以使用HashMap。例如:

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

从您向服务器请求的地方,您可以这样使用:

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);

答案 1 :(得分:0)

你可以像这样创建你的api

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

,基本网址为http://crb.cloud/mileage/api/