前面两讲我们已经把功能实现了,我们项目中使用的比较多的就是网络通信功能,而目前最流行的就是Retrofit网络通信框架。现在我们使用retrofit网络通信框架把项目整合一下。
首先介绍一下Retrofit:有一篇文章介绍这个框架非常详细,在这里放一个链接:https://blog.youkuaiyun.com/carson_ho/article/details/73732076
相信大家看完一定对Retrofit有了一个非常全新的认识。
下面我们开始使用Retrofit对项目进行改造!
第一步:添加依赖:
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.okhttp3:okhttp:3.1.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
第二步:创建接收服务器返回数据的类
package com.example.student.model;
/**
* Created by MHD on 2018/12/4.
* <p>文件描述:步骤二:创建用于接收服务器返回数据的类<p>
*/
public class Student {
private String id;
private String username;
private String chinese;
private String english;
private String math;
private String tel;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getChinese() {
return chinese;
}
public void setChinese(String chinese) {
this.chinese = chinese;
}
public String getEnglish() {
return english;
}
public void setEnglish(String english) {
this.english = english;
}
public String getMath() {
return math;
}
public void setMath(String math) {
this.math = math;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
第三步:创建用于描述网络请求的接口:
package com.example.student.service;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.GET;
import retrofit2.http.HTTP;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
/**
* Created by MHD on 2018/12/4.
* <p>文件描述:步骤三:创建接口设置,请求类型与参数<p>
* Retrofit把 网络请求的URL 分成了两部分设置:
* // 第1部分:在网络请求接口的注解设置"service/getIpInfo.php"
* // 第2部分:在创建Retrofit实例时通过.baseUrl()设置 .baseUrl("http://ip.taobao.com")
* 所以完整的接口应该是:http://ip.taobao.com/service/getIpInfo.php
* // 即:Retrofit支持动态改变网络请求根目录<p>
*/
public interface ApiService {
// @GET注解的作用:采用Get方法发送网络请求
// 其中返回类型为Call<*>,*是接收数据的类(即上面定义的GetInfoResponse类)
// 如果想直接获得Responsebody中的内容,可以定义网络请求返回值为Call<ResponseBody>
//一、GET类型不含参数
@GET("/students/query/")
// getCall()是接受网络请求数据的方法
Call<ResponseBody> getAllStudent();
//二、GET、DELETE类型含参数
//@GET("/student/query/")
//这里要通过用户输入的id拼接缺省的url,所以这里使用@Http
//作用:替换@GET、@POST、@PUT、@DELETE、@HEAD注解的作用 及 更多功能拓展
//具体使用:通过属性method、path、hasBody进行设置
@HTTP(method = "GET",path = "/student/query/{id}",hasBody = false)
Call<ResponseBody> getSingleStudent(@Path("id") String id);
@HTTP(method = "DELETE",path = "/student/delete/{id}",hasBody = false)
Call<ResponseBody> deleteSingleStudent(@Path("id") String id);
//二、POST、PUT类型含参数
@Headers({"Content-Type: application/json","Accept: application/json"})
@POST("/student/add")
Call<ResponseBody> addStudent(@Body RequestBody body);
@Headers({"Content-Type: application/json","Accept: application/json"})
@HTTP(method = "PUT",path = "/student/update/{id}",hasBody = true)
Call<ResponseBody> updateStudent(@Path("id") String id,@Body RequestBody body);
}
上面注解的具体解释在我上面放的那个链接里面都有,大家想具体了解的可以去看一下。
第四步:创建Retrofit实例:
//步骤4:创建Retrofit对象\
Retrofit retrofit=new Retrofit.Builder()
.baseUrl("http://192.168.1.159:8089")
.addConverterFactory(GsonConverterFactory.create())
.build();
第五步:创建网络请求接口实例并且对发送请求进行封装(一共5个):
1、请求全部学生:
// 步骤5:创建 网络请求接口 的实例
ApiService request=retrofit.create(ApiService.class);
//对发送请求进行封装(即调用接口方法)
retrofit2.Call<ResponseBody> call=request.getAllStudent();
2、根据id请求单个学生:
// 步骤5:创建 网络请求接口 的实例
ApiService requestSingle=retrofit.create(ApiService.class);
//对发送请求进行封装(即调用接口方法)
retrofit2.Call<ResponseBody> call=requestSingle.getSingleStudent(id);
3、添加一个学生:
// 步骤5:创建 网络请求接口 的实例
ApiService post=retrofit.create(ApiService.class);
//对发送请求进行封装(即调用接口方法)
RequestBody body=RequestBody.create(MediaType.parse("application/json; charset=utf-8"),json);
retrofit2.Call<ResponseBody> call=post.addStudent(body);
这里比之前的多了一个请求体,这个请求体跟我们之前使用OkHttp时是一样的。
4、删除一个学生:
//5、创建接口实例
ApiService delete=retrofit.create(ApiService.class);
//封装请求方法
retrofit2.Call<ResponseBody> call=delete.deleteSingleStudent(id);
5、修改一个学生:
//5、创建接口实例
ApiService delete=retrofit.create(ApiService.class);
//封装请求方法
retrofit2.Call<ResponseBody> call=delete.deleteSingleStudent(id);
第六步:发送网络请求(异步)
第七步:处理返回的数据
//步骤6:发送网络请求(异步)
call.enqueue(new retrofit2.Callback<ResponseBody>() {
@Override
public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
// 步骤7:处理返回的数据结果
try {
String responseData=response.body().string();
changeWithJSONObject(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
System.out.println(t);
}
});
以上内容经过测试均正常!!
关于Retrofit通信库的介绍就到这儿。
本文档介绍了如何使用Retrofit网络通信框架整合Java后台接口与Android客户端,实现学生成绩管理功能。包括添加依赖、创建接收数据类、定义网络请求接口、创建Retrofit实例、封装网络请求方法以及处理返回数据的步骤。
3694





