首页
登录 | 注册

Android Retrofit 接入——post方式发送表单,返回数据转换为JavaBean(一)

对于Retrofit,一直都没用过,因为一直在使用自己封装的Okhttp3.0 来实现网络请求,最近接到一个比较简单的项目,想着,就当作学习了,在项目中接入Retrofit,本文章只是简单接入Retrofit 。调试接口。

Retrofit 官方地址

官方中有简单的接入方法:

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

GitHubService service = retrofit.create(GitHubService.class);

对于这些注释的解释,网上也有很多博主写的文章介绍,自行百度。

首先在grade中导入:

    //Retrofit
   compile 'com.squareup.retrofit2:retrofit:2.2.0'
    //将返回的结果转换为JavaBean   Gson
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
    //转换为String
    compile 'com.squareup.retrofit2:converter-scalars:2.0.0'

Retrofit的初始化

 Retrofit  retrofit = new Retrofit.Builder()
                .baseUrl(QpAddress.baseUrl)
                .addConverterFactory(ScalarsConverterFactory.create())//将返回数据转化为String的转换器
                .addConverterFactory(GsonConverterFactory.create())//将返回数据转化为JavaBean的转换器
                .build();

  QpApiService      mApiService = retrofit.create(QpApiService.class);

QpAddress

注意这里的网址必须以”/”结束,不然会报错

Caused by: java.lang.IllegalArgumentException: baseUrl must end in /: http://api.club.auldey.com/aCloud/index.php


 Caused by: java.lang.IllegalArgumentException: baseUrl must end in /: http://api.club.auldey.com/aCloud/index.php```
public class QpAddress {
    public  static  String baseUrl;
    public  static void  setDebug(boolean isDebug){

        if (isDebug){
            baseUrl="http://192.168.199.105:8090/aCloud/index.php/";
        }else {
            baseUrl="http://api.club.auldey.com/";
        }
    }
}

QpApiService

public interface QpApiService {
    /**
     * 获取广告轮播图
     * @param map  a=api
     *             method=customized.thread.design
     *             moduleid=10
     *             appid=9FprO7RiGjFknxPo,
     *             random=ica3gjycxqy2
     *             tick=1521600960
     *             sign=NWNjMzY3MDY0ODQ2NmI4OTMyYWNhYzkyNDMyMjJkODg2ZmY3YWQwMw==
     * @return
     */
    @FormUrlEncoded
    @POST("aCloud/index.php")
    Call<BaseData<List<BannerBean>>> getBanners(@FieldMap Map<String, String> map);
}

返回的son 数据如下

{
  "code":"0",
  "info":[
    {
      "data_id":"91127",
      "title":"【规则】奥飞俱乐部发帖规则1.0",
      "url":"http://mobile.club.auldey.com/index/thread/tid/6752/fid/6.html",
      "thumb":"http://club.auldey.com/attachment/module/10/4f491059de7e0d5.jpg"
    },
    {
      "data_id":"91140",
      "title":"感谢陪伴丨我们永远在你身边",
      "url":"http://club.auldey.com/read.php?tid=6255&fid=6&page=1",
      "thumb":"http://club.auldey.com/attachment/module/10/d0f66945ae37988.jpg"
    },
    {
      "data_id":"93474",
      "title":"超级飞侠——出行安全小贴士",
      "url":"http://mobile.club.auldey.com/index/thread/tid/6758/fid/2.html",
      "thumb":"http://club.auldey.com/attachment/module/10/37c3d85bff5c866.jpg"
    }
  ]
}

最外层是一个JSONObject,然后info 对应则是JSONArray.
这时如果想让放回的数据直接转换为JavaBean,就需要一个BaseData先将数据解析JavaBean

BaseData


public class BaseData<T> {

    /**
     * {"code":"0","info":data}
     */

    private String code;
    private T info;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public T getInfo() {
        return info;
    }

    public void setInfo(T info) {
        this.info = info;
    }

    @Override
    public String toString() {
        return "BaseData{" +
                "code='" + code + '\'' +
                ", info=" + info +
                '}';
    }
}

BannerBean
将这个JSON转换为JavaBean

{
      "data_id":"91127",
      "title":"【规则】奥飞俱乐部发帖规则1.0",
      "url":"http://mobile.club.auldey.com/index/thread/tid/6752/fid/6.html",
      "thumb":"http://club.auldey.com/attachment/module/10/4f491059de7e0d5.jpg"
}
public class BannerBean {

    private String data_id;
    private String title;
    private String url;
    private String thumb;

    public String getData_id() {
        return data_id;
    }

    public void setData_id(String data_id) {
        this.data_id = data_id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getThumb() {
        return thumb;
    }

    public void setThumb(String thumb) {
        this.thumb = thumb;
    }

    @Override
    public String toString() {
        return "BannerBean{" +
                "data_id='" + data_id + '\'' +
                ", title='" + title + '\'' +
                ", url='" + url + '\'' +
                ", thumb='" + thumb + '\'' +
                '}';
    }
}

执行

//生成一个post的map集合,可以自己写一个HashMap来实现
    QpPostMap qpPostMap=new QpPostMap.Builder().
                addMethod("customized.thread.design")
                .addModuleid("10")
                .addAppid("9FprO7RiGjFknxPo")
                .addRandom("ica3gjycxqy2")
                .addTick("1521600960")
                .addSign("NWNjMzY3MDY0ODQ2NmI4OTMyYWNhYzkyNDMyMjJkODg2ZmY3YWQwMw==")
                .build();

 mApiService.getBanners(qpPostMap.getMap()).enqueue(new Callback<BaseData<List<BannerBean>>>() {
            @Override
            public void onResponse(Call<BaseData<List<BannerBean>>> call, Response<BaseData<List<BannerBean>>> response) {
                BaseData<List<BannerBean>> baseData = response.body();
                LogUtils.e("获取的数据==" + baseData.toString());

            }

            @Override
            public void onFailure(Call<BaseData<List<BannerBean>>> call, Throwable t) {

            }
        });

打印的数据如下:

这样就实现简单的使用Retrofit 实现数据请求。并将返回的数据转化为JavaBean



2020 jeepxie.net webmaster#jeepxie.net
10 q. 0.009 s.
京ICP备10005923号