retrofit的简单使用

retrofit的简单使用

Retrofit + gson + okhttp 实现图像聊天机器人

数据接口是聚合数据,主要是为了学习retrofit的网络请求和根据大牛大代码来提高自己代码能力,下面分析几个参考的博客
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/1016/3588.html
http://www.jianshu.com/p/5bc866b9cbb9

1.Android Studio加入具体的依赖

    //okhttp网络请求
    compile 'com.squareup.okhttp3:okhttp:3.3.1'
    //retrofit
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    //gson解析库
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.squareup.retrofit2:converter-gson:2.2.0'

当然也可以在官网找到最新的版本
https://github.com/square/retrofit
http://square.github.io/okhttp/

2.根据返回的json格式定义javabean对象

{
    "reason":"成功的返回",
    "result": /*根据code值的不同,返回的字段有所不同*/
        {
            "code":100000, /*返回的数据类型,请根据code的值去数据类型API查询*/
            "text":"你好啊,希望你今天过的快乐"
        },
     "error_code":0
}

根据上面的数据格式可以自己手动定义javabean或者http://www.jsonschema2pojo.org/转换,这里手动生成下面的javabean对象

public class ReplyRobot {

    @SerializedName("reason")
    private String reason;

    @SerializedName("result")
    private Result result;

    @SerializedName("error_code")
    private String error_code;


    public String getReason() {
        return reason;
    }

    public Result getResult() {
        return result;
    }

    public String getError_code() {
        return error_code;
    }

    @Override
    public String toString() {
        return "ReplyRobot{" +
                "reason='" + reason + '\'' +
                ", result=" + result.toString() +
                ", error_code='" + error_code + '\'' +
                '}';
    }
}


public class Result {

        @SerializedName("code")
        private int code;

        @SerializedName("text")
        private String text;

        public int getCode() {
            return code;
        }

        public String getText() {
            return text;

        }

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

3.根据请求网址格式定义接口

public interface RobotApi {
   //完整的请求是 http://op.juhe.cn/robot/index?info=你好&key=您申请到的APPKEY 我们分为两部分 
    public static final String BASE_URL = "http://op.juhe.cn/";
    //这里更换成你自己注册得到的聚合数据key
    public static final String APPKEY = "xxxxxxxxxxxxxxxxxxxx";
    //每次请求必填的只有2项,appkey和你的问题
    @GET("robot/index")
    Call<ReplyRobot> getReply(
            @Query("key") String appKey,
            @Query("info") String question
    );

}

4.使用retrofit对象生产请求接口

    public static final RobotApi apiService = new Retrofit.Builder()
            .baseUrl(RobotApi.BASE_URL)
            .client(new OkHttpClient.Builder().build())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(RobotApi.class);

5.使用接口进行异步操作获取数据填充到UI上

            //拿到接口
            Call<ReplyRobot> call = NetUtils.apiService.getReply(RobotApi.APPKEY , input);
            //进行异步操作
            call.enqueue(new Callback<ReplyRobot>() {
                //得到结果后
                @Override
                public void onResponse(Call<ReplyRobot> call, Response<ReplyRobot> response) {
                    if(response.isSuccessful()){
                        String r= response.body().getResult().getText();
                        Msg reply = new Msg(r , Msg.TYPE_RECEIVED);
                        chatAdapter.getmData().add(reply);
                        chatAdapter.notifyDataSetChanged();
                        Log.e(TAG, "onResponse: "+r);
                    }else {
                        Msg reply = new Msg("出错了" , Msg.TYPE_RECEIVED);
                        chatAdapter.getmData().add(reply);
                        chatAdapter.notifyDataSetChanged();
                        Log.e(TAG, "onResponse: "+"error" );
                    }
                }
                @Override
                public void onFailure(Call<ReplyRobot> call, Throwable t) {
                    ToastUtils.with(MainActivity.this).show("出现了错误");
                }
            });

6.github上该项目的代码

https://git.oschina.net/qianlilo/chatRobot.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值