[TOC]
# 0、简介
![Retrofit简介](http://upload-images.jianshu.io/upload_images/944365-b6d3198d37590906.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240 "Retrofit简介")<bookstack-summary></bookstack-summary>
# 1、导入依赖包
gradle.xml
```
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.0' //由于Retrofit是依赖于okhttp3,使用需要导入okhttp3的依赖包
```
#2、添加网络权限
AndroidMainfest.xml
```
<uses-permission android:name="android.permission.INTERNET" />
```
# 3、创建用于描述网络请求的接口
```
public interface TranslationService {
@GET("ajax.php?a=fy&f=auto&t=auto")
Call<Translation> translate(@Query("w") String query);
@POST("translate?doctype=json&jsonversion=&type=&keyfrom=&model=&mid=&imei=&vendor=&screen=&ssid=&network=&abtest=")
@FormUrlEncoded
Call<Translation1> translate1(@Field("i") String target);
}
```
# 4、创建Retrofit实例
MainActivity.java
```
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://fy.iciba.com/")
.addConverterFactory(GsonConverterFactory.create()) //Gson转换器,需要导入依赖 implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
.build();
```
# 5、创建网络请求接口的实例,并配置网络请求的参数
MainActivity.java
```
TranslationService service = retrofit.create(TranslationService.class);
```
# 6、发送网络请求(同步、异步)
# 7、处理返回解决(或异常)
MainActivity.java
```
Call<Translation> call = service.translate(data);
call.enqueue(new Callback<Translation>() { // 发送网络请求
//请求成功时回调
@Override
public void onResponse(Call<Translation> call, Response<Translation> response) {
showTV.setText(response.body().show());
}
//请求失败时回调
@Override
public void onFailure(Call<Translation> call, Throwable t) {
Log.e(TAG, "连接服务器失败! ");
Toast.makeText(MainActivity.this, "连接服务器失败!", Toast.LENGTH_SHORT).show();
}
});
```
# Retrofit的拓展使Retrofit的拓展使用
Retrofit支持Rxjava和prototocobuff
```
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://fy.iciba.com/")
.addConverterFactory(GsonConverterFactory.create()) //Gson转换器,需要导入依赖 implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
.addConverterFactory(ProtoConverterFactory.create()) // 支持Prototocobuff解析
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支持RxJava
.build();
```