1.Retrofit2请求库
添加依赖:
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.okhttp3:okhttp:3.5.0'
定义接口,该接口用来定义接受的数据类型与请求的参数:
public interface GetService {
@POST("url")
Call<RoomInfo> getRoomInfo(@Query("action") String action,
@Query("userId") String userId,
@Query("userName") String userName,
@Query("userAvatar") String userAvatar,
@Query("liveCover") String liveCover,
@Query("liveTitle") String liveTitle);
@POST("url")
Call<List<RoomInfo>> getRoomInfoList(@Query("action") String action,@Query("pageIndex") int pageIndex);
@POST("url")
Call<String> quitLiving(@Query("action") String action,
@Query("roomId") int roomId,
@Query("userId") String userId);
@POST("url")
Call<String> joinLiving(@Query("action") String action,
@Query("userId") String userId,
@Query("roomId") int roomId);
}
如上文可见,泛型Call方法里面可以接任何的返回类型,这是从后台接收到的数据,也为一个个对象,方法里面的参数是接的url,例如上述joinLiving("add","1",2)方法翻译成url即为:url?action=add&userId=1&roomId=2
也可以写成:
Call<RoomInfo> getRoomInfo(@body(RoomInfo roominfo));直接请求一个对象
POST可以用GET等其它操作替换,roomServlet是请求的
建立请求:
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
GetService request = retrofit.create(GetService.class);
//对发送请求进行封装
Call<String> call = request.quitLiving("quit",roomId,userId);
//发送网络请求(异步)
call.enqueue(new Callback<String>() {
//请求成功时回调
@Override
public void onResponse(Call<String> call, Response<String> response) {
}
//请求失败时回调
@Override
public void onFailure(Call<String> call, Throwable throwable) {
}
});
2.okhttp请求库
添加依赖:
compile 'com.squareup.okhttp3:okhttp:3.5.0'
定义数据解析类:
public class ResponseObject {
public static final String CODE_SUCCESS = "1";
public static final String CODE_FAIL = "0";
public String code;
public String errCode;
public String errMsg;
public List<RoomInfo> data;
}
该类为接受后台传过来的数据格式一致
建立请求,进行数据解析:
final Request request = new Request.Builder()
.url("url")
.build();
okClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//不是UI线程
if (response.isSuccessful()) {
LiveListResponseObj liveListresponseObject = gson.fromJson(response.body().string(), LiveListResponseObj.class);
} else {
onResponseFail(response.code());
}
}
});
推荐使用Retrofit2网络框架,因为前者封装了后者,而且前者结构清晰,思维明确。