使用retrofit2.0实现网络请求post和get请求

本文介绍如何使用Retrofit进行JSON数据和键值对数据的传输,包括定义接口、转换工具类及具体实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实例代码于百度云-一些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相同


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值