一、Retrofit2
二、Retrofit2概念
使用square公司开发的android和java的类型安全http客户端。
三、使用
1、retrofit官网:[http://square.github.io/retrofit/](https://link.jianshu.com/?t=http://square.github.io/retrofit/)
2、github地址:[https://github.com/square/retrofit](https://link.jianshu.com/?t=https://github.com/square/retrofit)
3、环境配置
在builde.gradle里面添加上
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
4、在AndroidManifest.xml添加所需权限
<uses-permission android:name="android.permission.INTERNET" />
四、基本使用
1、注册接口(API.class)
@GET("query")
Call<ResponseBody> getUserInfo();
//可以是Object对象,例:
//@GET("query")
//Call<Result> getUserInfo();
2、接口实现(建立连接)
Retrofit retrofit2 = new Retrofit.Builder()
.baseUrl("http://www.kuaidi100.com/")
.addConverterFactory(GsonConverterFactory.create())//自动转换JSON需引入依赖 com.squareup.retrofit2:converter-gson
.build();
API api = retrofit2.create(API.class);
.baseUrl设置最基本url,也就是http请求的url前缀,可以把项目中重复的前缀用这个来设置
.addConverterFactory(GsonConverterFactory.create())是添加Gson数据解析
3、获取接口数据(使用)
/**
* 测试
*/
Call<ResponseBody> call = api.getUserInfo();
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String result = response.body().string();
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
ResponseBody 这个是okhttp里面的对象,可以直接返回整个字符串,也可以获取流的形式
/**
// * 获取用户信息
// */
// api.getUserInfo().enqueue(new Callback<Result>() {
// @Override
// public void onResponse(Call<Result> call, Response<Result> response) {
// Toast.makeText(MainActivity.this, response.body().getMessage(), Toast.LENGTH_LONG).show();
// Toast.makeText(MainActivity.this, response.body().getStatus(), Toast.LENGTH_SHORT).show();
// }
//
// @Override
// public void onFailure(Call<Result> call, Throwable t) {
//
// }
// });
五、注解使用
1、创建Interface接口(API.class)
public interface API {
@GET("api/openapi/BaikeLemmaCardApi?scope=103&format=json&appid=379020&bk_key=银魂&bk_length=600")
Call<ResponseBody> getTextUser();
@GET("api/openapi/BaikeLemmaCardApi")
Call<Result> getUserInfoQuery(@Query("scope") int scope, @Query("format") String format, @Query("appid") int appid, @Query("bk_key") String bk_key, @Query("bk_length") int bk_length);
@GET("api/{openapi}/{BaikeLemmaCardApi}")
Call<Result> getUserInfoPath(@Path("openapi") String openapi, @Path("BaikeLemmaCardApi") String BaikeLemmaCardApi, @Query("scope") int scope, @Query("format") String format, @Query("appid") int appid, @Query("bk_key") String bk_key, @Query("bk_length") int bk_length);
@GET("api/{openapi}/{BaikeLemmaCardApi}")
Call<Result> getUserInfoQueryMap(@Path("openapi") String openapi, @Path("BaikeLemmaCardApi") String BaikeLemmaCardApi, @QueryMap Map<String, String> params);
@POST("api/openapi/BaikeLemmaCardApi")
Call<Result> savaUser(@Body Info info);
@FormUrlEncoded
@POST("api/openapi/BaikeLemmaCardApi")
Call<Result> editUser(@Field("scope") int scope, @Field("format") String format, @Field("appid") int appid, @Field("bk_key") String bk_key, @Field("bk_length") int bk_length);
}
2、接口实现(建立连接)
Retrofit retrofit2 = new Retrofit.Builder()
.baseUrl("http://baike.baidu.com/")
.addConverterFactory(GsonConverterFactory.create())//自动转换JSON需引入依赖 com.squareup.retrofit2:converter-gson
.build();
API api = retrofit2.create(API.class);
3、获取接口数据(使用)
/**
* GET获取用户信息 @Query
*/
api.getUserInfoQuery(103, "json", 379020, "银魂", 600).enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
Toast.makeText(MainActivity.this, response.body().getKey(),Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, response.body().getDesc(), Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<Result> call, Throwable t) {
}
});
/**
* GET获取用户信息 @Path ,@Query
*/
api.getUserInfoPath("openapi", "BaikeLemmaCardApi", 103, "json", 379020, "银魂", 600).enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
Toast.makeText(MainActivity.this, response.body().getSubLemmaId() + "", Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, response.body().getNewLemmaId() + "", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<Result> call, Throwable t) {
}
});
/**
* GET获取用户信息 @Path , @QueryMap
*/
Map<String, String> map = new HashMap<>();
map.put("scope", "103");
map.put("format", "json");
map.put("appid", "379020");
map.put("bk_key", "银魂");
map.put("bk_length", "600");
api.getUserInfoQueryMap("openapi", "BaikeLemmaCardApi", map).enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
Toast.makeText(MainActivity.this, response.body().getSubLemmaId() + "银", Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, response.body().getNewLemmaId() + "魂", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<Result> call, Throwable t) {
}
});
/**
* POST获取用户信息 @Body JSON提交方式
*/
Info info = new Info(103, "json", 379020, "银魂", 600);
api.savaUser(info).enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
Toast.makeText(MainActivity.this, response.body().getSubLemmaId() + "银Json", Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, response.body().getNewLemmaId() + "魂Json", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<Result> call, Throwable t) {
}
});
/**
* POST获取用户信息 @FormUrlEncoded @Field From提交方式
*/
Info info1 = new Info(103, "json", 379020, "银魂", 600);
api.savaUser(info1).enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
Toast.makeText(MainActivity.this, response.body().getSubLemmaId() + "银From", Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, response.body().getNewLemmaId() + "魂From", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<Result> call, Throwable t) {
}
});
六、与RxJava结合使用
好处:
1、代码整洁
2、易维护
1、环境配置
在builde.gradle里面添加依赖(Retrofit2基础上)
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
2、在Retrofit2建立连接的基础上添加红色部分代码
Retrofit retrofit2 = new Retrofit.Builder()
.baseUrl("http://www.kuaidi100.com/")
.addConverterFactory(GsonConverterFactory.create())//自动转换JSON需引入依赖 com.squareup.retrofit2:converter-gson
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())//与RxJava2结合使用
.build();
API api = retrofit2.create(API.class);
3、创建 Interface接口(API.class)
@POST("api/openapi/BaikeLemmaCardApi")
Observable<Result> loginWithRx(@Body Info info);
4、获取接口数据(使用)
/**
* 与RxJava结合使用
*/
api.loginWithRx(info).subscribe(new Observer<Result>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Result value) {
Toast.makeText(MainActivity.this, value.getSubLemmaId() + "银Observer", Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, value.getNewLemmaId() + "魂Observer", Toast.LENGTH_LONG).show();
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
温馨提示:与RxJava结合使用具体参考 RxJava2
网友评论