retrofit介绍
Retrofit与okhttp共同出自于Square公司,retrofit就是对okhttp做了一层封装。把网络请求都交给给了Okhttp,我们只需要通过简单的配置就能使用retrofit来进行网络请求了,其主要作者是Android大神JakeWharton
有兴趣的可以到官网查看:
retorfit官网
retrofit使用
导包
直接build gradle里添加依赖就可以了:
//Retrofit2所需要的包
compile ‘com.squareup.retrofit2:retrofit:2.0.0-beta4’
//ConverterFactory的Gson依赖包
compile ‘com.squareup.retrofit2:converter-gson:2.0.0-beta4’
//ConverterFactory的String依赖包
compile ‘com.squareup.retrofit2:converter-scalars:2.0.0-beta4’
使用
Retrofit提供的请求方式注解有@GET和@POST,参数注解有@PATH和@Query等
详细的注解对应的解释及处理方式
可参考此文章:http://blog.csdn.net/fuhao476200/article/details/52980318
Get请求
示例:
创建RetrofitNetService业务访问接口添加如下注解:
@GET("goods/{id}")
Call<ResponseBody> getgoods(@Path("id") int id);
Call ,此处T是返回的数据类型,如知道则可填写相对应的类型,如不知则可用泛型代替,或者ResponseBody代替。
@Path用于替换Url路径中的变量字符,这里的参数id会被填充至{id}中,形成完整的Url请求地址,{id}相当于一个占位符;
示例:
@GET("book/search")
Call<BookSearchResponse> getSearchBooks( @Query("name") String name, @Query("tag") String tag);
@Query
用于拼接在Url路径后的查询参数,但相对于直接在Url后拼接,@Query则是添加一个变量:类似BaseUrl+book/search?name={name}&type={type}
推荐:
类型及对应url模式可以查看
@QueryMap与Query一样,只不过是多个参数示例:
@GET("News")
Call<NewsBean> getItem(@QueryMap Map<String, String> map);
或者
@GET("News")
Call<NewsBean> getItem( @Query("newsId") String newsId,@QueryMap Map<String, String> map);
post请求
@Post post请求大约有四种方式,常用的就两种,
以键值对表单提交方式:
@FormUrlEncoded
@POST("Comments/{newsId}")
Call<Comment> reportComment(
@Path("newsId") String commentId,
@Query("access_token") String access_token,
@Field("reason") String reason);
@body类型提交方式:
RequestBody
//登入接口 @Headers({"Contenttype:application/json;charset=UTF-8"})
@POST("login")
Call<LoginReturnBean> loginApp(@Body RequestBody requestBody);
添加header
使用注解的方式
添加一个Header参数
@Headers({"Contenttype:application/json;charset=UTF-8"})
@GET("/tasks")
Call<List<Task>> getTasks();
添加多个Header参数
@Headers({
"Accept: application/vnd.yourapi.v1.full+json",
"User-Agent: Your-App-Name"
})
@GET("/tasks/{task_id}")
Call<Task> getTask(@Path("task_id") long taskId);
动态添加Header
@FormUrlEncoded
@POST("checkout")
Call<CheckOutResponse> checkout(@Header("userid") String userId, @FieldMap Map<String, String> params);
统一添加header
使用代码的方式,则需要使用拦截器
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("token", "a")
.header("tokenb","b")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
}
OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
简单分装
**
* @创建者 wyj
* @创建时间 2017/11/8 10:22.
* @描述
* @更新者
* @更新时间 2017/11/8 10:22.
*/
public class RetrofitUtil {
private static Retrofit retrofit;
private static OkHttpClient.Builder sHttpClient;
private static OkHttpClient sClient;
/**
* @return retrofit 实例
*/
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
synchronized (Retrofit.class) {
retrofit = new Retrofit.Builder()
.baseUrl(Url.BaseUrl) .addConverterFactory(GsonConverterFactory.create())
.client(getOkHttpClient())
.build();
}
}
return retrofit;
}
private static OkHttpClient getOkHttpClient() {
if (sHttpClient == null) {
sHttpClient = new OkHttpClient.Builder();
sHttpClient.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.addHeader("token","efgh")
.addHeader("code","abcd")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
});
if (sClient == null) {
sClient = sHttpClient.build();
}
}
return sClient;
}
/**
* @return 接口实例
*/
public static RetrofitNetService getHttpServiceInstance() {
return getRetrofitInstance().create(RetrofitNetService.class);
}
}
使用方式:
RetrofitNetService httpServiceInstance = RetrofitUtil.getHttpServiceInstance();
RequestBody bod2y = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),GsonTools.createGsonString(loginBody));
Call<LoginReturnBean> call = httpServiceInstance.loginApp(bod2y);
//同步请求
/* try {
Response<LoginReturnBean> execute = call.execute();
} catch (IOException e) {
e.printStackTrace();
}*/
//异步请求
call.enqueue(new Callback<LoginReturnBean>() {
@Override
public void onResponse(Call<LoginReturnBean> call, Response<LoginReturnBean> response) {
if (response.isSuccessful()) {
LoginReturnBean body =response.body();
}
}
@Override
public void onFailure(Call<LoginReturnBean> call, Throwable t) {
}
});
关于http的一些基础知识:
http://www.jianshu.com/p/e544b7a76dac
使用方法参考文章:
http://www.jianshu.com/p/331f0bf161c2
http://www.jianshu.com/p/308f3c54abdd