Retrofit的进阶之路(一)
Retrofit的进阶之路(二)添加请求头和上传图片
Retrofit+Rxjava的完美结合
这篇文章将给大家讲解如何添加统一的请求头和如何进行图片的上传
1、添加请求头
1)、对某个单一的Api加入Header
@Headers({
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-your-App"})‘
@GET("top250")
Call getTopMovie(@Query("start") int start, @Query("count") int count);
2)、添加统一的请求头
public static OkHttpClient genericClient() {
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
.addHeader("Accept-Encoding", "gzip, deflate")
.addHeader("Connection", "keep-alive")
.addHeader("Accept", "*/*")
.addHeader("Cookie", "add cookies here")
.build();
return chain.proceed(request);
}
})
.build();
return httpClient;
}
然后再new Retrofit时添加上即可
Retrofit retrofit2 = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(AddHeader2.genericClient())//添加头文件
.build();
2、上传图片
大家都知道在2.0以前版本上传图片的是这样子的
public interface ApiManager {
@Multipart
@POST("/user/addCarInfo")
void addCarInfo(@QueryMap Map options, @Part("file") TypedFile file, Callback response);
}
使用2.0,我们发现以前的TypedFile类型被私有化了 ,无法继续使用1.9的传方式,因此2.x提供了上传方案,可以MultipartBody.Part代替。
public interface FileUploadService {
@Multipart
@POST("upload")
Call upload(@Part("description") RequestBody description,
@Part MultipartBody.Part file);
}
一起来看下它的用法:
// 创建 RequestBody,用于封装构建RequestBody
RequestBody requestFile =equestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part 这里的partName是用image
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
// 添加描述
String descriptionString = "hello, 这是文件描述";
RequestBody description =
RequestBody.create(
MediaType.parse("multipart/form-data"), descriptionString);
// 执行请求
Call call = service.upload(description, body);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call,
Response response) {
Log.v("Upload", "success");
}
@Override
public void onFailure(Call call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});
}