1. 程式人生 > >Retrofit初探——POST方式提交JSON資料

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 ——