一、搭建联网框架
使用Retrofit2搭建项目的网络请求框架之前,我们需要先导入相关的三方库
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'io.reactivex:rxjava:1.2.1'
1、发起请求
Retrofit2向web服务器发起请求的方式有两种----Call 和rxjava
- Call
Call是Retrofit2库里发起请求的方法,使用这种方式我们可以使用execute来进行同步请求,enqueue来进行异步请求,cancel来取消请求。实际的使用过程:
Retrofit 初始化
public static final String baseUrl = "http://192.168.100.214:8090/peakBusiness/"; //内网
//--接口请求
private static NetworkService api;
public static NetworkService api() {
if (api == null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
api = retrofit.create(NetworkService.class);
}
return api;
}
定义接口请求的方法
@GET("front/user.htm")
Call<ReceiveData.BaseResponse > login(@QueryMap Map<String, String> options);
返回数据解析
//登录
public static class BaseResponse {
public int code;
public String msg;
}
接口调用
private void login(String loginName,String password) {
Map<String, String> options = new HashMap<>();
options.put("method", "login");
options.put("token", "123121");
options.put("loginName", loginName);
options.put("password", password);
RestClient.api().login(options).enqueue(new Callback<ReceiveData.loginResponse>() {
@Override
public void onResponse(Call<ReceiveData.loginResponse> call, Response<ReceiveData.loginResponse> response) {
if (response.body() == null) {
ToastUtil.showLong(LoginActivity.this,"登录异常", Gravity.CENTER);
return;
}
if (response.body().code == 0) {
ToastUtil.showLong(LoginActivity.this,"登录成功", Gravity.CENTER);
Gson gson = new Gson();
MyApplication.getInstance().setUserInfo(gson.toJson(response.body().obj));
finish();
}else {
ToastUtil.showLong(LoginActivity.this,response.body().msg, Gravity.CENTER);
}
}
@Override
public void onFailure(Call<ReceiveData.loginResponse> call, Throwable t) {
dialog.dismiss();
ToastUtil.showLong(LoginActivity.this,"登录失败",Gravity.CENTER);
}
});
}
- rxjava
RxJava响应式编程框架,基于观察者模式。使用这种方式进行请求我们主要使用到了ObServable(被观察者)和Subscribe(观察者),关于RxJava和Observable的讲解可以查看这篇文章RxJava—Observable
实际的使用过程:
Retrofit 初始化(HttpMethods.java)
public static final String BASE_URL = "http://192.168.100.132:8080/cnbsExamInterface/";
private static final int DEFAULT_TIMEOUT = 15;
private NetworkService networkService;
public static final int SuccessCode = 0;
//构造方法私有
private HttpMethods() {
OkHttpClient httpClient = new OkHttpClient.Builder()
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.build();
networkService = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(httpClient)
.build()
.create(NetworkService.class);
}
//在访问HttpMethods时创建单例
private static class SingletonHolder {
private static final HttpMethods INSTANCE = new HttpMethods();
}
//获取单例
public static HttpMethods getInstance() {
return SingletonHolder.INSTANCE;
}
private void toSubscribe(Observable o, Subscriber s) {
o.subscribeOn(Schedulers.io()) // 指定 subscribe() 发生在 IO 线程
.observeOn(AndroidSchedulers.mainThread()) // 指定 Subscriber 的回调发生在主线程
.subscribe(s);
}
//----------请求方法------------
//登录
public void login(Subscriber<HttpResult.LoginResponse> subscriber, Map<String, String> options) {
Observable observable = networkService.login(options);
toSubscribe(observable, subscriber);
}
定义接口请求的方法(NetworkService.java)
//登录
@GET("front/logAct/log.html")
Observable<HttpResult.LoginResponse> login(@QueryMap Map<String, String> options);
返回数据解析(HttpResult.java)
public static class BaseResponse {
public String code;
public String msg;
}
接口调用
private void login(String user,String psw) {
Map<String, String> map = new HashMap<>();
map.put("loginName", user);
map.put("passWord", psw);
HttpMethods.getInstance().login(new Subscriber<HttpResult.LoginResponse>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
new CenterHintToast(LoginActivity.this,"登录失败,稍后重试!");
}
@Override
public void onNext(HttpResult.LoginResponse response) {
if ("0".equals(response.code)) {
UserBean bean = response.user;
MyApplication instance = MyApplication.getInstance();
instance.setUserInfo(bean);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
} else {
new CenterHintToast(LoginActivity.this, response.msg);
}
}
}, map);
}
二、Retrofit2.0 注解的使用
- 好文链接 Retrofit各个注解的含义及作用
- 下面是常用的注解
1、Get请求
使用@GET注解,@Query 或 @QueryMap参数注解,示例:
@GET("apisiness/inspectTasks/inspectTask")
Observable<HttpResult.TaskDownResponse> downTask(@QueryMap Map<String, String> options);
2、Post请求
使用@POST注解,@Field 或 @FieldMap参数注解,示例:
@POST("apisiness/inspectTasks/uploadTask")
Observable<HttpResult.TaskUploadResponse> uploadTask(@FieldMap Map<String, String> options);
@Multipart
@POST("apisiness/uploadAct/uploadImgs")
Observable<HttpResult.TaskUploadResponse> uploadAdjunct(@FieldMap <String, String> options, @Part() List<MultipartBody.Part> parts);
Post请求还有以下常用的注解:
@Field和FieldMap -- 参数注解,用于发送一个表单请求。
@FormUrlEncoded -- 用于修饰Field注解和FieldMap注解,使用该注解,表示请求正文将使用表单网址编码。
@Multipart -- 表示请求体是多部分的。 每一部分作为一个参数,且用Part注解声明。
@Part -- 参数注解,用于定义Multipart请求的每个part,参数值可以为空,为空时,则忽略。
使用该注解定义的参数类型有以下3种方式可选:
- 如果类型是okhttp3.MultipartBody.Part,内容将被直接使用。 省略part中的名称,即 @Part MultipartBody.Part part ;
- 如果类型是RequestBody,那么该值将直接与其内容类型一起使用。 在注释中提供part名称(例如,@Part(“img”)RequestBody img);
- 其他对象类型将通过使用转换器转换为适当的格式(如实体Bean对象的上传)。 在注释中提供part名称(例如,@Part(“Image ”)Image photo)。
三、RxJava处理嵌套请求
这里就要用到RxJava的操作符flatMap了。以下代码实现了上传图片和设置用户头像的两个接口的嵌套使用,Demo代码如下:
Map<String, String> options = new HashMap<>();
options.put("type", "userHeadImg");
Map<String, RequestBody> obj = new HashMap<>();
RequestBody photo = RequestBody.create(MediaType.parse("image/png"), os.toByteArray());
obj.put("Imgs\"; filename=\"icon.png", photo);
RestClient.oapi().oUploadPic(options,obj)
.flatMap(new Func1<ReceiveData.OUpPhotoResponse, Observable<ReceiveData.OBaseResponse>>() {
@Override
public Observable<ReceiveData.OBaseResponse> call(ReceiveData.OUpPhotoResponse oUpPhotoResponse) {
thumPath = oUpPhotoResponse.piclist.get(0).getImg_path();
Map<String, String> options = new HashMap<>();
options.put("method", "updateImg");
options.put("userId", 5+"");
options.put("headImg",thumPath);
return RestClient.omapi().oResetUserImg(options);
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<ReceiveData.OBaseResponse>() {
@Override
public void call(ReceiveData.OBaseResponse oBaseResponse) {
if (oBaseResponse.code == 0){
showInfo.setText("嵌套请求成功!!");
userimg.setImageURI(RestClient.imgUrl+thumPath);
}
}
});
四、拦截器&Basic认证
有两种添加方式,一种是在每一个接口中加;第二种是在拦截器中加。
1、认证加密信息
private String username = "$";
private String password = "$";
// basic认证信息
String credentials = username + ":" + password;
final String basic = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
2、在接口中添加认证信息
接口传参时,将上面的加密信息传递给接口,再进行调用即可。
@GET("loginAct/loginByVerifyCode.html")
Observable<HttpResult.BaseResponse> base(@Header("Authorization") String auth,@QueryMap Map<String, String> options);
3、在拦截器中添加认证信息
public class InterceptorUtils{
//给请求添加一个头
public static Interceptor HeaderInterceptor(final String basic) {
return new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder builder = request.newBuilder();
builder.addHeader("authorization", basic);
return chain.proceed(builder.build());
}
};
}
}
4、实际使用
public class HttpMethods {
private static final int DEFAULT_TIMEOUT = 15;
public NetworkService networkService;
private String username = "$";
private String password = "$";
// basic认证信息
String credentials = username + ":" + password;
final String basic = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
private static HttpMethods httpMethodsods;
//构造方法私有
private HttpMethods() {
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(InterceptorUtils.HeaderInterceptor(basic))
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.build();
//防止修改的url不合理
try {
networkService = new Retrofit.Builder()
.baseUrl(MyApplication.getInstance().getBaseURL())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(httpClient)
.build()
.create(NetworkService.class);
}catch (Exception e){
e.printStackTrace();
}
}
...
五、错误解决
1、post请求返回400
现象:retrofit2.0 post提交一直返回400,用httpurlconnection就可以
原因:我使用的post方式有问题,虽然我使用了@post标识这个请求,但是我传参的地方用错标签了,@QueryMap是用于get请求的传参标签,把他换成post的传参标签@FieldMap就好了。
- 错误的使用
@POST("front/questionnaireResultsAct/resultSave.html")
Observable<HttpResult.UploadResponse> uploadData(@QueryMap <String, String> options);
- 正确的使用
@FormUrlEncoded
@POST("front/questionnaireResultsAct/resultSave.html")
Observable<HttpResult.UploadResponse> uploadData(@FieldMap Map<String, String> options);