一. 简要介绍
二 .导入依赖
三. GET请求—无参
四. GET请求—传参
五. POST请求
六. @Url的使用
七. 文件上传
7.1单文件上传
7.2多文件上传
八. 文件和参数一起上传
九. Form表单形式上传
十. 文件下载
十一. 请求头注解
一. 简要介绍
Retrofit其实我们可以理解为OkHttp的加强版,它是一个网络加载框架。底层是使用OKHttp封装的。准确来说,网络请求的工作本质上是OkHttp完成,而 Retrofit 仅负责网络请求接口的封装。它的一个特点是包含了特别多注解,方便简化你的代码量。
二. 导入依赖
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.7.0'
三. GET请求无传参
不使用Gson
- 首先, 需要有一个API接口, 注解形式
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
/**
* Created by Yzr on 2020/10/30
*/
public interface API {
@GET("/retrofit/get")
Call<ResponseBody> getJson();
}
- 网络请求(GET方式)
private void getRequest() {
// 屏蔽证书
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), new TrustAllCerts()) // 信任所有证书
.hostnameVerifier(new TrustAllHostnameVerifier())
.connectTimeout(10, TimeUnit.SECONDS) // 超时时间
.build();
// 创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl("https://192.168.1.6:1718")
.build();
API api = retrofit.create(API.class);
Call<ResponseBody> task = api.getJson();
task.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(@NotNull Call<ResponseBody> call, @NotNull Response<ResponseBody> response) {
Log.e("TAG", "responseCode: " + response.code());
if (response.code() == HttpURLConnection.HTTP_OK) {
try {
Log.e("TAG", "json: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(@NotNull Call<ResponseBody> call, @NotNull Throwable t) {
Log.e("TAG", "onFailure: " + t);
}
});
}
使用Gson
- 创建bean类(接收服务器传来的Json数据)
public class JsonResult {
/**
* result : true
* note : 查询成功
* data : {"uid":1,"phone_number":"123456788","username":"Biu丶Yang","salt":"b94e71d68b3bd062f5127d3a43b1d268b2b487d8f9e00fe3298b9d86bb798b78","points":"7866","head_view":"thumbnailImg/1/20201012105003.jpeg","background_wall":"thumbnailImg/1/20200808153732.jpeg","birth":"1997-6-17","sex":"男"}
*/
private boolean result;
private String note;
private DataBean data;
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public static class DataBean {
/**
* uid : 1
* phone_number : 12332112311
* username : Biu丶Yang
* salt : b94e71d68b3bd062f5127d3a43b1d268b2b487d8f9e00fe3298b9d86bb798b78
* points : 7866
* head_view : thumbnailImg/1/20201012105003.jpeg
* background_wall : thumbnailImg/1/20200808153732.jpeg
* birth : 1997-6-17
* sex : 男
*/
private int uid;
private String phone_number;
private String username;
private String salt;
private String points;
private String head_view;
private String background_wall;