1. 程式人生 > >使用retrofit2.0實現網路請求post和get請求

使用retrofit2.0實現網路請求post和get請求

例項程式碼於百度雲-一些androiddemo

   compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'


1.傳輸json型別資料到服務端

retrofit的介面:

@Headers({"Content-Type:application/json;charset=utf-8", "Accept:application/json;"})
    @POST("json/reply/AgencyLoginRequest")
    Call<LoginBean> postAgencyLogin(@Body RequestBody route);//實現json格式的傳輸

一些工具類:資料MD5加密,bean轉json等:

package com.example.administrator.testrxjava;

import com.google.gson.Gson;

/**
 * Created by Administrator on 2016/4/15.
 *
 * Gson封裝類
 */
public class GsonUtils {
    private static Gson gson;

    static {
        if (gson == null) {
            gson = new Gson();
        }
    }

    /**
     * 物件轉Json字串
     *
     * @param object
     * @return
     */
    public static String toJson(Object object) {
        checkGson();
        return gson.toJson(object);
    }

    /**
     * 字串轉Json物件
     *
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        checkGson();
        return gson.fromJson(json, clazz);
    }

    private static void checkGson() {
        if (gson == null) {
            gson = new Gson();
        }
    }

}

使用:

 private void login() {
        Map<String, String> map = new HashMap<>();
        map.put("Phone", "15888888888");
        map.put("Password", CommonUtils.encodeMD5("123456").toUpperCase());
        map.put("AccountId", "");
        map.put("WxOpenId", "");
        map.put("Source", "3");
        map.put("Timestamp", CommonUtils.getUTC());
        map.put("IpAddress", "");
        map.put("MachineNo", "123456");
        Retrofit retrofit = new Retrofit.Builder().baseUrl(BaseHttp.Base_url).addConverterFactory(GsonConverterFactory.create()).build();

        HttpApiS httpApiS = retrofit.create(HttpApiS.class);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), CommonUtils.convertPostJson(map));
        retrofit2.Call<LoginBean> call = httpApiS.postAgencyLogin(requestBody);
        call.enqueue(new retrofit2.Callback<LoginBean>() {
            @Override
            public void onResponse(retrofit2.Call<LoginBean> call, retrofit2.Response<LoginBean> response) {
                LoginBean loginBean = response.body();
                if (loginBean.getIsSuccess() == 1) {
                    Log.e("登入成功", "===========");
                } else {
                    Log.e("登入失敗", "============");
                }
            }

            @Override
            public void onFailure(retrofit2.Call<LoginBean> call, Throwable t) {

            }
        });

    }


2.傳輸鍵值對型別到服務端

介面:

   //實現鍵值對形式的傳輸
    @POST("/yos/user/user_login.ysmd?")
    @FormUrlEncoded
    Call<LoginBeanTwo> postLoginTwo(@Field("user.bu_mobile") String mobile, @Field("user.bu_password") String password);//實現json格式的傳輸
    //鍵值對傳輸的第二種方法
    @POST("/yos/user/user_login.ysmd?")
    @FormUrlEncoded
    Call<LoginBeanTwo> doLogin(@FieldMap Map<String,String> params);

呼叫:

  private void loginTwo() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(BaseHttp.Base_url2).addConverterFactory(GsonConverterFactory.create()).build();
        HttpApiS httpApiS = retrofit.create(HttpApiS.class);
        Map<String, String> map = new HashMap<>();
        map.put("user.bu_mobile", "15539158137");
        map.put("user.bu_password", "123456");
        retrofit2.Call<LoginBeanTwo> call = httpApiS.doLogin(map);
        call.enqueue(new retrofit2.Callback<LoginBeanTwo>() {
            @Override
            public void onResponse(retrofit2.Call<LoginBeanTwo> call, retrofit2.Response<LoginBeanTwo> response) {
                LoginBeanTwo loginBeanTwo = response.body();
                if (loginBeanTwo == null) {
                    Log.e("請求失敗", "====");
                    Log.e("===", loginBeanTwo.getInformation() + "");
                } else {
                    Log.e("===", loginBeanTwo.getInformation() + "");
                    Log.e("請求成功", "====");
                    if (loginBeanTwo.getError().equals("0000")) {
                        Log.e("登入成功", "===");
                    } else {
                        Log.e("登入失敗", "====");
                    }
                }


            }

            @Override
            public void onFailure(retrofit2.Call<LoginBeanTwo> call, Throwable t) {
                Log.e("請求返回失敗", t.getMessage() + "=");
            }
        });
    }

二:get請求

引數可以單寫,也可以map寫,只距離map的

   /*使用get來獲取*/
    //多引數,用map,註解用@QueryMap
    @GET("/call.aspx?forward=16-1603&caller=M")
    Observable<Bean_get> getInfo(@QueryMap Map<String,String> params);
呼叫的方法和post相同