Retrofit与okhttp共同出自于Square公司,retrofit就是对okhttp做了一层封装。把网络请求都交给给了Okhttp,我们只需要通过简单的配置就能使用retrofit来进行网络请求了,其主要作者是Android大神JakeWharton
有兴趣的可以到官网查看:
retorfit官网
直接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
示例:
创建RetrofitNetService业务访问接口添加如下注解:
@GET("goods/{id}")
Call getgoods(@Path("id") int id) ;
Call ,此处T是返回的数据类型,如知道则可填写相对应的类型,如不知则可用泛型代替,或者ResponseBody代替。
@Path用于替换Url路径中的变量字符,这里的参数id会被填充至{id}中,形成完整的Url请求地址,{id}相当于一个占位符;
示例:
@GET("book/search")
Call 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 getItem(@QueryMap Map<String, String> map);
或者
@GET("News")
Call getItem( @Query("newsId") String newsId,@QueryMap Map<String, String> map);
@Post post请求大约有四种方式,常用的就两种,
以键值对表单提交方式:
@FormUrlEncoded
@POST("Comments/{newsId}")
Call 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 loginApp(@Body RequestBody requestBody);
添加一个Header参数
@Headers({"Contenttype:application/json;charset=UTF-8"})
@GET("/tasks")
Call> getTasks()
;
@Headers({
"Accept: application/vnd.yourapi.v1.full+json",
"User-Agent: Your-App-Name"
})
@GET("/tasks/{task_id}")
Call getTask(@Path("task_id") long taskId) ;
@FormUrlEncoded
@POST("checkout")
Call<CheckOutResponse> checkout(@Header("userid") String userId, @FieldMap Map<String, String> params);
使用代码的方式,则需要使用拦截器
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 call = httpServiceInstance.loginApp(bod2y);
//同步请求
/* try {
Response execute = call.execute();
} catch (IOException e) {
e.printStackTrace();
}*/
//异步请求
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful()) {
LoginReturnBean body =response.body();
}
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
关于http的一些基础知识:
http://www.jianshu.com/p/e544b7a76dac
使用方法参考文章:
http://www.jianshu.com/p/331f0bf161c2
http://www.jianshu.com/p/308f3c54abdd