Post raw json in body retrofit2

Post raw json in body retrofit2

我想要 post json 那样的请求

{"jsonrpc": "2.0", "method": "testApi", "params": { "message": "abc" } , "id": 1}

我阅读了posts:

How to POST raw whole JSON in the body of a Retrofit request?

但我无法在我的 retrofit2 包中找到 class TypedInput、TypedByteArray、TypedString。在哪里?

对于 POST Retrofit 中的一个主体,您创建一个表示该主体的对象,一个包含 String jsonrpcString method 等的 class . 然后,将此对象传递给您在服务接口中定义的方法,该方法有一个带有 @Body 注释的参数。

下面是 POST 正文对象的示例:

public class PostBody{

   String jsonprc;
   String method;
   Param param;

   public PostBody(...){
        //IMPLEMENT THIS
   }

   ...

   class Param{
       //IMPLEMENT THIS
   }

}

POST 数据到服务器需要后端程序 也就是 post 你的 数据到服务器中的数据库.....

改造 Post 需要 RESTAPI 和 POJO Class ....

API 界面

public interface Api {
    @POST("/upload/{new}.json")
    Call<User> setData(@Path("new") String s1, @Body User user);
}

改造对象

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("here-your-url")
                .addConverterFactory(GsonConverterFactory.create()) 
                .build(); 

APi 对象

Api api = retrofit.create(Api.class);

改造调用

Call<User> call = api.setData("mahesh", new User("mahesh", "delhi"));
    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            t1.setText("Success");
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
            Log.d("sam", "fail");
            t1.setText("fail");
        }
    });

POJO class //你创建的这个class只是将你的json数据放入这个POJOConvertion

public class User {

    String name;
    String address;

    public User(String name, String address) {
        this.address = address;
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

享受编码。

如果你想对 Retrofit 进行任何练习,请使用这个 Retrofit + Firebase