首页 > 解决方案 > 为什么我在 Retrofit2 按 id 删除数据时收到 IllegalArgumentException 错误?以及如何解决?

问题描述

我正在尝试通过 Java、Retrofit、PHP、MySQL 的 id 参数删除 phpmyadmin 中的用户。当我按下删除按钮时,在 Logcat 中我得到了这个错误

 java.lang.IllegalArgumentException: URL query string "id={id}" must not have replace block. For dynamic query parameters use @Query.
    for method UsersAPI.deletePost

用户API.java

import retrofit2.Call;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.Path;

public interface UsersAPI {

    @GET("users_read.php")
    Call<List<User>> getUsers();

    @DELETE("delete_user.php?id={id}")
    Call<Void> deletePost(@Path("id") int id);
}

AdminActivity.java:这是删除按钮的监听器:

btnDeleteUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int deleteId = Integer.parseInt(editTextDeleteUser.getText().toString());
                Call<Void> call = usersAPI.deletePost(deleteId);
                call.enqueue(new Callback<Void>() {
                    @Override
                    public void onResponse(Call<Void> call, Response<Void> response) {
                        Toast.makeText(AdminActivity.this,"Response code: "+response.code(),Toast.LENGTH_SHORT).show();
                        return;
                    }

                    @Override
                    public void onFailure(Call<Void> call, Throwable t) {
                        Toast.makeText(AdminActivity.this, "Error : "+ t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
            });

为什么我会收到此错误?以及如何解决它。先感谢您。

标签: javaphpandroidretrofit2

解决方案


替换这个:

 @DELETE("delete_user.php?id={id}")
Call<Void> deletePost(@Path("id") int id);

有了这个

 @DELETE("delete_user.php")
Call<Void> deletePost(@Query("id") int id);

@Path 用于构建动态端点,但对于 Query,您需要查询注释。


推荐阅读