Retrofit的简单使用
简单介绍
- 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 到 你好世界 的翻译
本文详细介绍了Retrofit的使用方法,包括添加依赖、创建数据模型类、定义接口、创建Retrofit实例及发送网络请求等步骤,展示了如何利用Retrofit进行翻译功能的网络请求。
3382

被折叠的 条评论
为什么被折叠?



