【问题标题】:How to Call this webservice in Retrofit如何在 Retrofit 中调用这个 web 服务
【发布时间】:2018-01-01 17:55:44
【问题描述】:

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

我的服务端点:

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

我的代码:

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

【问题讨论】:

  • 改进的帖子和格式

标签: android web-services retrofit


【解决方案1】:

您可以使用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);

【讨论】:

  • 显示响应码 404
  • 显示同样的错误
【解决方案2】:

你可以像这样创建你的 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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 2020-01-14
    相关资源
    最近更新 更多