Android中Retrofit2.0如何使用JSON進行數(shù)據(jù)交互

這篇文章主要介紹了Android中Retrofit 2.0如何使用JSON進行數(shù)據(jù)交互,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

成都創(chuàng)新互聯(lián)公司專注于納雍企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè)公司,購物商城網(wǎng)站建設(shè)。納雍網(wǎng)站建設(shè)公司,為納雍等地區(qū)提供建站服務(wù)。全流程按需策劃,專業(yè)設(shè)計,全程項目跟蹤,成都創(chuàng)新互聯(lián)公司專業(yè)和態(tài)度為您提供的服務(wù)

之前使用Retrofit都是將JSON串轉(zhuǎn)化為POJO對象,針對不同的業(yè)務(wù)協(xié)議,定義相應(yīng)的接口和參數(shù)列表。但是此種方式一般用在自己內(nèi)部協(xié)議基礎(chǔ)上,具體大的項目中,有些第三方的集成功能,一般都采用統(tǒng)一的方式即請求JSON和回應(yīng)JSON進行數(shù)據(jù)交互,不可能每個第三方協(xié)議都會去定義與協(xié)議相應(yīng)的POJO對象。

HTTP肯定有GET和POST方法,先定義Retrofit Api的interface:

package com.hdnetworklib.network.http;

import java.util.Map;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.QueryMap;
import retrofit2.http.Url;

/**
 * Created by wangyuhang@evergrande.cn on 2017/8/23 0023.
 */

public interface RetrofitServiceApi {
  @POST
  Call<ResponseBody> reqPost(@Url String url, @Body RequestBody requestBody);

  @GET
  Call<ResponseBody> reqGet(@Url String url, @QueryMap Map<String, String> options);

  @GET
  Call<ResponseBody> reqGet(@Url String url);
}

1、POST方式,采用指定完整的URL,reqeustBody就是后面業(yè)務(wù)要傳入的完整JSON串

2、GET方式,后面的options就是一個Map,業(yè)務(wù)參數(shù)鍵值就存在這個里面,URL里面不需要帶值。

3、GET方式,與2不同的是沒有options,這樣就鍵值對全部帶在URL里面,類似于這樣的格式:http://112.124.22.238:8081/course_api/wares/hot?pageSize=1&curPage=1

接下來就是具體對業(yè)務(wù)的接口了,提供POST和GET兩個請求接口調(diào)用:

package com.hdnetworklib.network.http;

import android.util.Log;

import java.io.IOException;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by wangyuhang@evergrande.cn on 2017/7/12 0012.
 */

public class HttpClient {
  private static final String TAG = "HttpClient";
  private static volatile HttpClient instance;

  private HttpClient() {
  }

  public static HttpClient getInstance() {
    if (instance == null) {
      synchronized (HttpClient.class) {
        if (instance == null) {
          instance = new HttpClient();
        }
      }
    }

    return instance;
  }

  /**
   * Http Post請求
   *
   * @param req_id  請求編號
   * @param method  請求業(yè)務(wù)方法
   * @param url   請求的URL
   * @param jsonData POST需要所帶參數(shù)(JSON串格式)
   * @param callback 回調(diào)接口
   */
  public void reqPostHttp(final int req_id, final String method, String url, String jsonData, final HttpCallback callback) {
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://www.what.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

    RetrofitServiceApi retrofitServiceApi = retrofit.create(RetrofitServiceApi.class);

    RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonData);

    Call<ResponseBody> call = retrofitServiceApi.reqPost(url, body);
    call.enqueue(new Callback<ResponseBody>() {
      @Override
      public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        try {
          String result = response.body().string();
          Log.i(TAG, "reqPostHttp onResponse: " + result);

          if (callback != null) {
            callback.onSuccess(new HttpResMsg(req_id, method, result));
          }
        } catch (IOException e) {
          e.printStackTrace();
          Log.e(TAG, "reqPostHttp onResponse exception: " + e.toString());

          if (callback != null) {
            callback.onError(e.toString());
          }
        }
      }

      @Override
      public void onFailure(Call<ResponseBody> call, Throwable t) {
        Log.e(TAG, "reqPostHttp onFailure: " + t.toString());

        if (callback != null) {
          callback.onError(t.toString());
        }
      }
    });
  }

  /**
   * Http Get請求
   *
   * @param req_id  請求編號
   * @param method  請求業(yè)務(wù)方法
   * @param url   請求的URL
   * @param options GET需要所帶參數(shù)鍵值(如果URL里帶有則不需要在此添加)
   * @param callback 回調(diào)接口
   */
  public void reqGetHttp(final int req_id, final String method, String url,
              Map<String, String> options, final HttpCallback callback) {
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://www.what.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

    RetrofitServiceApi retrofitServiceApi = retrofit.create(RetrofitServiceApi.class);

    Call<ResponseBody> call = null;
    if (options == null) {
      call = retrofitServiceApi.reqGet(url);
    } else {
      call = retrofitServiceApi.reqGet(url, options);
    }

    call.enqueue(new Callback<ResponseBody>() {
      @Override
      public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        try {
          String result = response.body().string();
          Log.i(TAG, "reqPostHttp onResponse: " + result);

          if (callback != null) {
            callback.onSuccess(new HttpResMsg(req_id, method, result));
          }
        } catch (IOException e) {
          e.printStackTrace();
          Log.e(TAG, "reqPostHttp onResponse exception: " + e.toString());

          if (callback != null) {
            callback.onError(e.toString());
          }
        }
      }

      @Override
      public void onFailure(Call<ResponseBody> call, Throwable t) {
        Log.e(TAG, "reqPostHttp onFailure: " + t.toString());
        if (callback != null) {
          callback.onError(t.toString());
        }
      }
    });
  }
}

需要注意的是:

baseUrl(http://www.what.com/)

這里的這個baseUrl是我瞎掰的一個地址,因為Retrofit的限制:如果baseUrl不是以 / 結(jié)尾就會報異常:

Caused by: java.lang.IllegalArgumentException: baseUrl must end in /

當我們需要完整的指定URL的時候,特別是上面列出的第二種GET方式,我們的URL是http://112.124.22.238:8081/course_api/wares/hot?pageSize=1&curPage=1,如果我們直接通過接口傳參把這個URL直接傳入baseUrl中,如下(注意最后沒有/結(jié)尾):

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://112.124.22.238:8081/course_api/wares/hot?pageSize=1&curPage=1")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

這樣運行時就會報錯。那如果我們手工在最后面加上一個/呢?如下(注意最后有/結(jié)尾):

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://112.124.22.238:8081/course_api/wares/hot?pageSize=1&curPage=1/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

這樣運行時仍然報錯,而且你把這個鏈接復制到瀏覽器中看看就知道肯定不行的:http://112.124.22.238:8081/course_api/wares/hot?pageSize=1&curPage=1/

我一開始遇到這個問題的時候也是第一反應(yīng)去查Retrofit的官方文檔和說明,或者讓第三方的開發(fā)人員采用第二種GET請求方式,用一個以 / 結(jié)尾的URL,然后把URL中?后面帶的那些值放到一個Map里傳進來。首先官方說明和Api用法沒找到,而且這個baseUrl還必須調(diào)用,其次,別的開發(fā)人員不愿意弄,好好的辛辛苦苦把URL都組裝好了,沒啥事讓我傳Map啊,肯定也不行。后面在這里找到了答案:https://stackoverflow.com/questions/36736854/retrofit2-how-do-i-put-the-at-the-end-of-the-dynamic-baseurl

Android中Retrofit 2.0如何使用JSON進行數(shù)據(jù)交互

Android中Retrofit 2.0如何使用JSON進行數(shù)據(jù)交互

所以既然你后面會完整指定URL,那么一開始的baseUrl就無關(guān)緊要,隨便寫一個以/結(jié)尾的Http地址就可以了。

剩下的的就是回調(diào)和消息的組裝了,各位可以根據(jù)自己的業(yè)務(wù)需求進行組裝和調(diào)整,我這里就只貼出代碼不做過多解析了。

回調(diào)接口:

package com.hdnetworklib.network.http;

/**
 * Created by wangyuhang@evergrande.cn on 2017/8/23 0023.
 */

public interface HttpCallback {
  void onSuccess(HttpResMsg httpResMsg);

  void onError(String errorMsg);
}

消息結(jié)構(gòu)的組裝:

package com.hdnetworklib.network.http;

/**
 * Created by wangyuhang@evergrande.cn on 2017/8/23 0023.
 */

public class HttpResMsg {
  private Integer req_id;
  private String method;
  private String data;

  public HttpResMsg() {
  }

  public HttpResMsg(int req_id, String method, String data) {
    this.req_id = req_id;
    this.method = method;
    this.data = data;
  }

  public Integer getReq_id() {
    return req_id;
  }

  public void setReq_id(Integer req_id) {
    this.req_id = req_id;
  }

  public String getMethod() {
    return method;
  }

  public void setMethod(String method) {
    this.method = method;
  }

  public String getData() {
    return data;
  }

  public void setData(String data) {
    this.data = data;
  }
}

感謝你能夠認真閱讀完這篇文章,希望小編分享的“Android中Retrofit 2.0如何使用JSON進行數(shù)據(jù)交互”這篇文章對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識等著你來學習!

當前名稱:Android中Retrofit2.0如何使用JSON進行數(shù)據(jù)交互
當前網(wǎng)址:http://muchs.cn/article8/pppgip.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動態(tài)網(wǎng)站、網(wǎng)站策劃、網(wǎng)站設(shè)計微信小程序、網(wǎng)站收錄、標簽優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)