Retrofit初探——POST方式提交JSON数据

0x00 HTTP Method:POST

POST请求再日常的使用中很常见,比如登录,上传数据中使用。之前介绍了GET方式,今天简单介绍下如何使用POST来提交数据。

0x01 常用的POST方式

POST方式提交数据再浏览器中的表现主要是使用Form,在客户端中国中的主要表现是提交JSON数据。当然,具体是什么数据格式并不重要,我们可以通过抓包来分析:最终数据都是一样的。

使用Model对象

首先新建一个model对象,比如:User,添加常用的熟悉和get/set方法。新建我们的Service:

@POST("/send")
public Call<ResponseBody> modelPost(@Url String url, @Body User user);

测试代码:

@Test
public void modelPost() throws Exception {
   HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
   logging.setLevel(HttpLoggingInterceptor.Level.BASIC);

   OkHttpClient client = RetrofitManager.getClient(logging);

   Retrofit retrofit = RetrofitManager.getRetrofit(client);
   ExampleService service = retrofit.create(ExampleService.class);

   String url = "http://www.remoteurl.com";
   User user = new User();
   user.setName("ttdevs");
   Call<ResponseBody> example = service.modelPost(url, user);

   final CountDownLatch countDownLatch = new CountDownLatch(1);
   example.enqueue(new Callback<ResponseBody>() {
       @Override
       public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
           try {
               print(response.body().string());
           } catch (IOException e) {
               e.printStackTrace();
           }

           countDownLatch.countDown();
       }

       @Override
       public void onFailure(Call<ResponseBody> call, Throwable t) {
           countDownLatch.countDown();
       }
   });
   countDownLatch.await();
}

使用RequestBody对象

这里我们来提交一份JSON数据,首先还是再Service中创建一个方法:

@POST("/send")
public Call<ResponseBody> withRequestBody(@Url String url, @Body RequestBody body);

再接着创建我们的请求:

@Test
public void withRequestBody() throws Exception {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BASIC);

    OkHttpClient client = RetrofitManager.getClient(logging);

    Retrofit retrofit = RetrofitManager.getRetrofit(client);
    ExampleService service = retrofit.create(ExampleService.class);

    String url = "http://www.remoteurl.com";

    JSONObject result = new JSONObject();
    try {
        result.put("record", "hello");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    RequestBody body = RequestBody.create(MediaType.parse("application/json"), result.toString());
    Call<ResponseBody> example = service.withRequestBody(url, body);

    final CountDownLatch countDownLatch = new CountDownLatch(1);
    example.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            try {
                print(response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }

            countDownLatch.countDown();
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            countDownLatch.countDown();
        }
    });
    countDownLatch.await();
}

总结

第一种方法,我们需要为每一个请求的对象创建一个Model,如果你不想创建model则可以选择第二种方式,直接创建一个JSON字符串,然后提交即可。还是相当简答的。

—— EOF ——

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
你可以使用 Retrofit提交 JSON 格式的数据。首先,你需要创建一个 Java 类来定义你要提交JSON 数据的结构。然后,你可以使用 Retrofit 的注解来定义请求的方式和路径,以及指定请求体的内容类型为 JSON。最后,你可以调用 Retrofit 的方法来发送请求。 下面是一个示例: 首先,定义一个 Java 类来表示要提交JSON 数据的结构,比如一个用户信息: ```java public class User { private String name; private String email; public User(String name, String email) { this.name = name; this.email = email; } } ``` 接下来,在 Retrofit 的 API 接口中定义请求的方式、路径和请求体的内容类型。使用 `@Body` 注解来指定请求体为 JSON 格式: ```java public interface ApiService { @POST("users") Call<Void> createUser(@Body User user); } ``` 然后,创建 Retrofit 实例并构建 API 接口的实现: ```java Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.example.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); ApiService apiService = retrofit.create(ApiService.class); ``` 最后,调用 API 接口的方法来发送请求: ```java User user = new User("John Doe", "john.doe@example.com"); Call<Void> call = apiService.createUser(user); call.enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { // 请求成功处理 } @Override public void onFailure(Call<Void> call, Throwable t) { // 请求失败处理 } }); ``` 这样,你就可以使用 Retrofit提交 JSON 格式的数据了。记得替换示例中的 URL 和路径为你实际的接口地址和路径。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值