使用POST方法在Retrofit api中传递参数问题

时间:2019-07-03 08:36:13

标签: java android api retrofit2

我想使用API​​从服务器获取通知。我正在使用Retrofit2与API配合使用。

问题是,当我在POST方法中传递参数时,我得到“ IllegalArgumentException URL不包含参数”。

该参数正确,并且可以在iOS中使用。我想在android中实现。

下面是调试应用程序时的结果。

      Caused by: java.lang.IllegalArgumentException: URL 
      "notification/newnotification" does not contain "{userid}". (parameter #1)

我尝试过更改参数,并也询问API开发人员。他说参数正确。

这是API接口的代码:

public interface API{
    @FormUrlEncoded
    @POST("notification/newnotification")
    Call<ResponseBody> getUserNotification(
        @Path("userid") int userid
    );
 }

RetrofitClient.java

public class RetrofitClient {

public static final String BASE_URL = "http://danceglobe.co/dance/api/";
private static RetrofitClient mInstance;
private Retrofit retrofit;

private RetrofitClient(){
    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
}

public static synchronized RetrofitClient getInstance(){
    if(mInstance == null) {
        mInstance = new RetrofitClient();
    }
    return mInstance;
}

public API getApi(){
    return retrofit.create(API.class);
}


}

从MainActivity调用函数

    private void getNotification(String currentUserId) {
    Call<ResponseBody> call = RetrofitClient.getInstance().getApi().getUserNotification(Integer.parseInt(currentUserId));
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if(!response.isSuccessful()){
                Toast.makeText(MainActivity.this,response.message(),Toast.LENGTH_SHORT).show();
            }

            try {
                String s = response.body().string();
                Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toast.makeText(MainActivity.this,t.getMessage(),Toast.LENGTH_SHORT).show();
        }
    });

}

我希望它响应一些数据。

请帮助我。我从过去两天开始就陷入困境。

2 个答案:

答案 0 :(得分:1)

 Caused by: java.lang.IllegalArgumentException: URL 
  "notification/newnotification" does not contain "{userid}". (parameter #1)

意味着您应该将userId添加到类似的路径

public interface API {
    @POST("notification/newnotification/{userid}")
    Call<ResponseBody> getUserNotification(
        @Path("userid") int userid
    );
}

@Path("userid")将变量映射到丢失的占位符{userid}

答案 1 :(得分:0)

我通过对API接口进行一些更改来使其工作。 下面是API接口的新代码

@FormUrlEncoded
@POST("notification/newnotification")
Call<ResponseBody> getUserNotification(
        @Field("userid") String userid   // changed line 
);