retrofit
底层由okhttp实现,相当于一个适配器。
使用的时候很简洁,解耦性很高。
retrofit中大量使用注解,所以用起来很方便。
使用retrofit要先知道
- 网络请求返回的是json/xml或其他格式的数据,所以需要自定义一个 接收服务器返回数据格式所对应的类
- 创建一个接口,用来描述网络请求,如用GET或是POST请求方式,要访问的url,设置请求头或参数等,接口中的方法必须要用注解进行
简单的使用步骤
以GET方式为例
1.使用retrofit需要先添加依赖
点击 project structure,——>Dependencies——>点击加号,选择Library dependency,输入retrofit,在列表中找到
和你的sdk版本适应的retrofit,点击确定
或者在dependencies中添加代码
implementation 'com.squareup.retrofit2:retrofit:2.6.0'
2.根据服务器返回的Json数据格式编写java类
public class Translation {
//根据不同需求编写
private int status;
private content content;
public void setOut(String out){
content.out = out;
}
public String getOut(){
return content.out;
}
private static class content{
private String from;
private String to;
private String vendor;
private String out;
private int errno;
}
3.创建描述网络请求的接口
public interface GetRequest_Interface
@GET("ajax.php?a=fy&f=auto&t=auto&w=follow%20system")
Call<Translation> getCall();
//注解里传入的是部分网络请求的url的地址,另一部分在retrofit对象的baseUrl中
//如果接口里的是完整的url 那么对象中就不用传入地址
//getcall是接受网络请求数据的方法
}
4.创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://fy.iciba.com/")//那么这里的url 放在接口的注解里应该也是可以的,
.addConverterFactory(GsonConverterFactory.create())//设置使用retrofit的gson解析
.build();
5.创建网络请求接口的实例
使用retrofit对象的方法,把我们设置的请求封装
GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
这就是请求对象
6.对请求进行封装
Call<Translation> call = request.getCall();
如果设置的有参数,就在getCall()方法里传参
7.异步发送网络请求,并对返回数据进行处理
call.enqueue(new Callback<Translation>() {
@Override
public void onResponse(Call<Translation> call, Response<Translation> response) {
String s = response.body().show();
//这就是服务器返回的数据
tv.setText(s);
Log.i("HTTP",s);
}
@Override
public void onFailure(Call<Translation> call, Throwable t) {
Log.i("HTTP","链接失败");
Log.i("HTTP",t.getMessage());
}
});