Retrofit是OkHttp的升级版 ,在其基础上再次封装的框架,使用起来更加的简便
添加依赖
github主页https://square.github.io/retrofit/
在build.gradle中添加代码
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
使用方式GET
1.创建Retrofit对象
//创建Retrofit
private Retrofit retrofit = new Retrofit.Builder()
//设置baseUrl (一个完整的url中,第一个/前面的就是baseUrl)
//http://apis.juhe.cn/xzpd/query ==> http://apis.juhe.cn
.baseUrl("http://apis.juhe.cn")
.build();
2.创建网络请求接口文件,并在其中声明请求方法
/**
* @author 83765
* 网络请求接口文件
*/
public interface GetApi {
/**
* 星座配对 参数使用Query方式 一般参数少就使用这个
* http://apis.juhe.cn/xzpd/query
* 使用get方式 @GET表示请求方法为GET,参数为相对路径,会拼接在baseUrl后面
*
* 在retrofit中没有设置CallAdapterFactory和ConverterFactory时,则返回值必须是 Call<ResponseBody>
*
* @Query("men") ==> 在url后面拼接 men=xxx xxx就是方法参数men的值
* 需要配合@GET使用,其他的请求方式(POST,PUT,DELETE等)不能使用Query或QueryMap
*/
@GET("/xzpd/query")
Call<ResponseBody> xzpd(@Query("men") String men, @Query("women") String women, @Query("key") String key);
/**
* 星座配对 参数使用QueryMap方式 一般参数比较多就使用这种
* http://apis.juhe.cn /xzpd/query
* 使用get方式
* 获取视频信息
* 在retrofit中没有设置CallAdapterFactory和ConverterFactory时,则返回值必须是 Call<ResponseBody>
*
* @QueryMap ==> 参数值必须是map类型,且key是字符串, 最终会将里面所有的key,value拼接在url后面
*/
@GET("/xzpd/query")
Call<ResponseBody> xzpd2(@QueryMap Map<String, String> params);
}
3.使用Retrofit创建接口实例对象
//使用retrofit.create方法,并传入我们定义的接口文件class,会返回这个接口的实例
GetApi getApi = retrofit. Create(GetApi.class);
4.调用接口1
//访问接口方法
Call<ResponseBody> call = getApi.xzpd(men, woman, "55e2473c92ce6f49074430d33e8db6cc");
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String json = response.body().string();
PeiduiResponse peiduiResponse = gson.fromJson(json, PeiduiResponse.class);
if (peiduiResponse != null && peiduiResponse.getResult() != null) {
PeiduiBean result = peiduiResponse.getResult();
runOnUiThread(new Runnable() {
@Override
public void run() {
tvResult.setText("");
tvResult.append("男生:"