Android框架|网络-Retrofit2.x(一)

Retrofit的简单使用


Retrofit官网
github源码

简单介绍

  • Retrofit 是一个 RESTful 的 HTTP 网络请求框架的封装,可以理解为OkHttp的加强版,网络请求的工作本质上是 OkHttp 完成,而Retrofit 只是负责网络请求接口的封装。

它的优点:

  • 1)支持RxJava
    2)支持注解化配置
    3)解耦
    4)支持同步&异步网络请求
    5) 支持多种数据的解析&序列化格式(Gson、 Json、XML)

get实现: 翻译功能
金山词霸api

1.添加依赖

compile 'com.squareup.retrofit2:retrofit:2.0.2'
    // Retrofit库
compile 'com.squareup.okhttp3:okhttp:3.1.2'
    // Okhttp库

2.添加网络权限

<uses-permission android:name="android.permission.INTERNET"/>

3.创建类

  • 用于接收服务器返回的数据

    public class Translation {
        private int status;
    
        private content content;
        public static class content {
            private String from;
            private String to;
            private String vendor;
            private String out;
            private int errNo;
            public String getOut() {
                return out;
            }
            public void setOut(String out) {
                this.out = out;
            }
        }
        public content getContent(){
            return content;
        }
        public void setContent(content content){
            this.content=content;
        }
    }
    

4.创建接口

  • 用于描述网络请求

    public interface GetRequest_Interface {
        //helloworld
        @GET("ajax.php?a=fy&f=auto&t=auto&w=hello%20world")
        Call<Translation> getCall();
    } 
    
  • @GET注解传入部分URL地址,一部分放在Retrofit对象里,另一部分放在网络请求接口里
    下面的 getCall()是自定义的接受网络请求数据的方法
    在接口里面采用注解来配置网络请求参数。用动态代理将该接口的注解“翻译”成一个Http请求,最后再执行 Http请求。

创建实例

  • 在Activity中创建Retrofit实例 记得加入Gson解析依赖:compile 'com.squareup.retrofit2:converter-gson:2.0.2'

    Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://fy.iciba.com/") // 设置 网络请求 Url
                    .addConverterFactory(GsonConverterFactory.create()) //使用Gson解析
                    .build(); 在Activity中创建网络请求接口实例
    
    GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);       
    Call<Translation> call = request.getCall();
    

发送网络请求

 call.enqueue(new Callback<Translation>() {
            //请求成功时回调
            @Override
            public void onResponse(Call<Translation> call, Response<Translation> response) {
                Log.i(TAG,"请求结果: "+response.body().getContent().getOut());
            }
            //请求失败时回调
            @Override
            public void onFailure(Call<Translation> call, Throwable throwable) {
                Log.i(TAG,"连接失败");
            }
        });

运行结果:
在这里插入图片描述
实现 hello world 到 你好世界 的翻译


参考文档

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值