Retrofit2 框架学习&Demo

本文介绍了如何使用Retrofit框架进行GET和POST网络请求,并详细解释了金山词霸、有道词典及淘宝IP查询API的具体调用过程。

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

1.Retrofit介绍
Retrofit是一个RESTful的HTTP网络请求框架基于OkHttp
功能:支持同步,异步网络请求
支持多种数据解析序列化格式(Gson,Json,XML,Protobuf)
通过注解配置网络请求参数
提供对RxJava的支持
项目网址:https://github.com/square/retrofit
下载:git clone https://github.com/square/retrofit.git
导入AS,添加库
build.gradle(Module:app)
dependencies {
compile ‘com.squareup.retrofit2:retrofit:2.3.0’
compile ‘com.squareup.retrofit2:converter-gson:2.3.0’ // 用Gson解析json的转换器
}

2.使用Retrofit的GET功能调用金山词霸的API在线翻译
参考:http://blog.youkuaiyun.com/carson_ho/article/details/73732076
金山词霸API 的数据格式说明如下:
// URL模板
http://fy.iciba.com/ajax.php

// URL实例
http://fy.iciba.com/ajax.php?a=fy&f=auto&t=auto&w=hello%20world
http://fy.iciba.com/ajax.php?a=fy&f=auto&t=auto&w=星期一
// 参数说明:
// a:固定值 fy
// f:原文内容类型,日语取 ja,中文取 zh,英语取 en,韩语取 ko,德语取 de,西班牙语取 es,法语取 fr,自动则取 auto
// t:译文内容类型,日语取 ja,中文取 zh,英语取 en,韩语取 ko,德语取 de,西班牙语取 es,法语取 fr,自动则取 auto
// w:查询内容

json示例
{
“status”:1, //请求成功时为1,失败为0
“content”:{ //内容信息
“from”:”zh-CN”, //原文内容类型
“to”:”en-US”, //译文内容类型
“out”:”Monday”, //译文内容
“vendor”:”ciba”, //来源平台
“err_no”:0 //请求成功取0
}
}
1)把json转成实体类,创建 接收服务器返回数据的类

public class Translation {

private int status;
private Content content;
public void setStatus(int status) {
     this.status = status;
 }
 public int getStatus() {
     return status;
 }

public void setContent(Content content) {
     this.content = content;
 }
 public Content getContent() {
     return content;
 }

}
public class Content {

private String from;
private String to;
private String out;
private String vendor;
private int err_no;
public void setFrom(String from) {
     this.from = from;
 }
 public String getFrom() {
     return from;
 }

public void setTo(String to) {
     this.to = to;
 }
 public String getTo() {
     return to;
 }

public void setOut(String out) {
     this.out = out;
 }
 public String getOut() {
     return out;
 }

public void setVendor(String vendor) {
     this.vendor = vendor;
 }
 public String getVendor() {
     return vendor;
 }

public void setErr_no(int err_no) {
     this.err_no = err_no;
 }
 public int getErr_no() {
     return err_no;
 }

}

2)创建 用于描述网络请求的接口
采用 注解 描述 网络请求参数

//Get请求网络接口

public interface GetRequest_Interface {
    //getCall()是接受请求数据的方法
    @GET("ajax.php?a=fy&f=auto&t=auto")
    Call<Translation> getCall(@Query("w") String word);
    //@Query 是查询ajax.php?a=fy&f=auto&t=auto&w=xxx
    // 注解里传入 网络请求 的部分URL地址
    // getCall()是接受网络请求数据的方法
}

3)请求网络
public void request(){
//1)创建Retrofit对象
String url =”http://fy.iciba.com/”;
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
//2)创建网络请求接口的实例
GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
//3)对 发送请求进行封装
Call call = request.getCall(edGet.getText().toString());
//4)发送异步网络请求

    public void request(){
        //1)创建Retrofit对象
        String url ="http://fy.iciba.com/";
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        //2)创建网络请求接口的实例
        GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
        //3)对 发送请求进行封装
        Call<Translation> call = request.getCall(edGet.getText().toString());
        //4)发送异步网络请求
        call.enqueue(new Callback<Translation>() {
            //请求成功时回调
            @Override
            public void onResponse(Call<Translation> call, Response<Translation> response) {
             String out =   response.body().getContent().getOut();

                tv.setText(out);
            }
            //请求失败时回调
            @Override
            public void onFailure(Call<Translation> call, Throwable t) {
                tv.setText("没有找到...请检查网络");
            }
        });
    }

3.使用Retrofit的POST功能调用有道词典的API在线翻译
API的数据格式如下
// URL
http://fanyi.youdao.com/translate

// URL实例
http://fanyi.youdao.com/translate?doctype=json&jsonversion=&type=&keyfrom=&model=&mid=&imei=&vendor=&screen=&ssid=&network=&abtest=
// 请求方式说明
// 请求方式:POST
// 请求体:i
// 请求格式:x-www-form-urlencoded

json示例
{
“type”:”ZH2EN_EN”,
“errorCode”:0,
“elapsedTime”:0,
“translateResult”:{
[
{
“src”:”天气真好”,
“tgt”:”It’s a nice day”
}
]
}
}

解析:
type:翻译类型
errorCode: 0 表示成功
translateResult:翻译结果
src:原文
tgt:译文

1)把json转成实体类,创建 接收服务器返回数据的类
public class TranslationDao {

/**
 * type : ZH2EN_EN
 * errorCode : 0
 * elapsedTime : 0
 * translateResult : [[{"src":"天气真好","tgt":"It's a nice day"}]]
 */

private String type;
private int errorCode;
private int elapsedTime;
private List<List<TranslateResultBean>> translateResult;

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public int getErrorCode() {
    return errorCode;
}

public void setErrorCode(int errorCode) {
    this.errorCode = errorCode;
}

public int getElapsedTime() {
    return elapsedTime;
}

public void setElapsedTime(int elapsedTime) {
    this.elapsedTime = elapsedTime;
}

public List<List<TranslateResultBean>> getTranslateResult() {
    return translateResult;
}

public void setTranslateResult(List<List<TranslateResultBean>> translateResult) {
    this.translateResult = translateResult;
}

public static class TranslateResultBean {
    /**
     * src : 天气真好
     * tgt : It's a nice day
     */

    private String src;
    private String tgt;

    public String getSrc() {
        return src;
    }

    public void setSrc(String src) {
        this.src = src;
    }

    public String getTgt() {
        return tgt;
    }

    public void setTgt(String tgt) {
        this.tgt = tgt;
    }
}

}
2)创建 用于描述网络请求的接口
采用 注解 描述 网络请求参数
public interface PostRequest_Interface {
@POST(“translate?doctype=json&jsonversion=&type=&keyfrom=&model=&mid=&imei=&vendor=&screen=&ssid=&network=&abtest=”)
@FormUrlEncoded
Call getCall(@Field(“i”) String targetSentence);
//采用@Post表示Post方法进行请求(传入部分url地址)
// 采用@FormUrlEncoded注解的原因:API规定采用请求格式x-www-form-urlencoded,即表单形式
// 需要配合@Field使用
}

@Field传输数据类型为键值对,常用的POST请求数据类型
首先用到@FormUrlEncoded注解来标明这是一个表单请求,在getCall方法中使用
@Field注解来标示所对应的String类型数据的键,从而组成一组键值对进行传递.

3)请求网络

public void request(){
//1)创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(“http://fanyi.youdao.com/“)
.addConverterFactory(GsonConverterFactory.create())
.build();
//2)创建 网络请求接口的实例
PostRequest_Interface request = retrofit.create(PostRequest_Interface.class);
//3)对发送请求,进行封装
Call call = request.getCall(edPost.getText().toString());
//4)发送异步网络请求
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
//处理返回的数据结果,输出翻译内容
String result = response.body().getTranslateResult().get(0).get(0).getTgt();
tvPost.setText(result);
}

        @Override
        public void onFailure(Call<TranslationDao> call, Throwable t) {

        }
    });

}

4.使用Retrofit的POST功能调用淘宝ip的API在线查询ip地址
参考:http://liuwangshu.cn/application/network/9-retrofit2.html
请求接口(GET):
/service/getIpInfo.php?ip=[ip地址字串]
响应信息:
(json格式的)国家 、省(自治区或直辖市)、市(县)、运营商
返回数据格式:

{“code”:0,”data”:{“ip”:”210.75.225.254”,”country”:”\u4e2d\u56fd”,”area”:”\u534e\u5317”,
“region”:”\u5317\u4eac\u5e02”,”city”:”\u5317\u4eac\u5e02”,”county”:”“,”isp”:”\u7535\u4fe1”,
“country_id”:”86”,”area_id”:”100000”,”region_id”:”110000”,”city_id”:”110000”,
“county_id”:”-1”,”isp_id”:”100017”}}

其中code的值的含义为,0:成功,1:失败。

1)把json转成实体类,创建 接收服务器返回数据的类
public class IpModel {

/**
 * code : 0
 * data : {"ip":"210.75.225.254","country":"中国","area":"华北","region":"北京市","city":"北京市","county":"","isp":"电信","country_id":"86","area_id":"100000","region_id":"110000","city_id":"110000","county_id":"-1","isp_id":"100017"}
 */

private int code;
private DataBean data;

public int getCode() {
    return code;
}

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

public DataBean getData() {
    return data;
}

public void setData(DataBean data) {
    this.data = data;
}

public static class DataBean {
    /**
     * ip : 210.75.225.254
     * country : 中国
     * area : 华北
     * region : 北京市
     * city : 北京市
     * county : 
     * isp : 电信
     * country_id : 86
     * area_id : 100000
     * region_id : 110000
     * city_id : 110000
     * county_id : -1
     * isp_id : 100017
     */

    private String ip;
    private String country;
    private String area;
    private String region;
    private String city;
    private String county;
    private String isp;
    private String country_id;
    private String area_id;
    private String region_id;
    private String city_id;
    private String county_id;
    private String isp_id;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public String getRegion() {
        return region;
    }

    public void setRegion(String region) {
        this.region = region;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCounty() {
        return county;
    }

    public void setCounty(String county) {
        this.county = county;
    }

    public String getIsp() {
        return isp;
    }

    public void setIsp(String isp) {
        this.isp = isp;
    }

    public String getCountry_id() {
        return country_id;
    }

    public void setCountry_id(String country_id) {
        this.country_id = country_id;
    }

    public String getArea_id() {
        return area_id;
    }

    public void setArea_id(String area_id) {
        this.area_id = area_id;
    }

    public String getRegion_id() {
        return region_id;
    }

    public void setRegion_id(String region_id) {
        this.region_id = region_id;
    }

    public String getCity_id() {
        return city_id;
    }

    public void setCity_id(String city_id) {
        this.city_id = city_id;
    }

    public String getCounty_id() {
        return county_id;
    }

    public void setCounty_id(String county_id) {
        this.county_id = county_id;
    }

    public String getIsp_id() {
        return isp_id;
    }

    public void setIsp_id(String isp_id) {
        this.isp_id = isp_id;
    }
}

}

2)创建 用于描述网络请求的接口
采用 注解 描述 网络请求参数
public interface IPRequest_Interface {
@Headers({
“Accept-Encoding: application/json”,
“User-Agent: MoonRetrofit”
})
@GET(“getIpInfo.php”)
Call getCall(@Query(“ip”) String ip);
//@Query就是请求的键值对的设置,@Query(“ip”)代表键
//String ip则代表值
//@Headers用来添加头部信息,上面用的是固定头部,也可以采用动态头部:
}

3)请求网络

public void request(){
//1)创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(“http://ip.taobao.com/service/“)
.addConverterFactory(GsonConverterFactory.create())
.build();
//2)创建 网络请求接口的实例
IPRequest_Interface request = retrofit.create(IPRequest_Interface.class);
Call call = request.getCall(edIp.getText().toString());
//3)用Call请求网络并处理回调
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
String Country = response.body().getData().getCountry();
String Provnce = response.body().getData().getRegion();
String City = response.body().getData().getCity();
tvIp.setText(“国家:”+Country+” 省份:”+Provnce+ ” 城市:”+City);
}

        @Override
        public void onFailure(Call<IpModel> call, Throwable t) {
            tvIp.setText("查询失败");
        }
    });


}

这里写图片描述
http://download.youkuaiyun.com/download/shui1025701856/10219384

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值