Retrofit使用

  




//這段代碼放到   業務層公共操作的封裝

  protected static ResponseInfoAPI responseInfoAPI;

  public Presenter() {

if (responseInfoAPI == null) {

            //網絡訪問
            //第一步,創建Builder,指定baseUrl和數據解析工具
            Retrofit.Builder reBuilder = new Retrofit.Builder();
            reBuilder.baseUrl(Constant.LOGIN); //指定要連接的網絡路徑
            reBuilder.addConverterFactory(GsonConverterFactory.create()); //指定要使用的解析方式
            //第二步創建 Retrofit
            Retrofit retrofit = reBuilder.build();
            //第三步 指定請求方式(get或post)和參數,通過以接口的形式指定
            //第三步 通過接口ResponseInfoAPI
            //第四步  將 Retrofit和第三步的聯網參數聯繫起來
            responseInfoAPI = retrofit.create(ResponseInfoAPI.class);

        }

}



public interface ResponseInfoAPI {
  //設置請求方式
    @GET(Constant.APISERVER)
    Call<ResponseInfo> login(@Query("username") String userName, @Query("password") String passWord);


  //首頁
  @GET(Constant.HOME)
  Call<ResponseInfo> home();


  //商品
  @GET(Constant.RECOMMENDINFO)
     Call<ResponseInfo>  reCommendInfo(@Query("sellerId") int sellerId);




  /*
  phone 電話
  type 登陸類型(必須)普通登陸:1;短信驗證:2;三方登錄:3


   */
  //手機驗證碼登錄
  @GET(Constant.SMSLOGIN)
  Call<ResponseInfo> smsLogin(@Query("phone") String phone,@Query("type") int type);


  //地址
  @GET(Constant.ADDRESS)
    Call<ResponseInfo> address(@Query("userId") int userId);


//提交訂單到服務器
  @FormUrlEncoded
  @POST(Constant.ORADER)
  Call<ResponseInfo> orader(@Field("orderOverview") String s);


  //支付
  @GET(Constant.PAY)
  Call<ResponseInfo> pay(@Query("orderId") String oraderNumber);


  @GET(Constant.ORADER)
    Call<ResponseInfo> orderList(@Query("userId") int userid);
}


public class Constant {
    public static final String LOGIN = "http://192.168.0.103:8080/";
    //登錄
    public static final String APISERVER="TakeoutService/login";
    //首頁
    public static final String HOME="TakeoutService/home";
    //商品   http://localhost:8080/TakeoutService/goods?sellerId=1
    public static final String RECOMMENDINFO = "TakeoutService/goods";
    //sms登錄
    public static final String SMSLOGIN="TakeoutService/login";




    public static final int SMSTYPE=2;  //驗證碼登錄


    //地址 http://localhost:8080/TakeoutService/address?userId=1794
    public static final String ADDRESS="TakeoutService/address";
    //提交訂單
    public static final String ORADER = "TakeoutService/order";
    //支付
    public static final String PAY = "TakeoutService/pay";



//添加Retrofit依賴:
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    // 使用Gson進行數據解析
    compile 'com.google.code.gson:gson:2.2.4'
    // 將Retorfit與Gson關聯
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
   
}



發佈了31 篇原創文章 · 獲贊 15 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章