废话不多说了直接上代码
请求工具类
public class AARetrofitUtil {
private static final String TAG = "retrofit";
//TODO:修改主机地址
private static final String BASE_URL = "服务器代码";
private static final int DEFAULT_TIMEOUT = 5 * 1000;//超时为五秒
private static Retrofit retrofit;
//实例化私有
private AARetrofitUtil() {
}
public static Retrofit getInstance() {
if (retrofit == null) {
ClearableCookieJar cookieJar =
new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(App.getInstance()));
OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder(); //okhttp创建,写入缓存机制,还有addInterceptor
httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
File cacheFile = new File(App.getInstance().getCacheDir(), "superman");
Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb
httpClientBuilder.cache(cache);
httpClientBuilder.cookieJar(cookieJar);
httpClientBuilder.addInterceptor(LoggingInterceptor);
httpClientBuilder.addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR);
httpClientBuilder.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR);
return new Retrofit.Builder() //retrofit的创建。
.client(httpClientBuilder.build()) //传入okhttp
.addConverterFactory(new NullOnEmptyConverterFactory())
.addConverterFactory(GsonConverterFactory.create()) //传入gson解析手段
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
//传入异步手段
.baseUrl(BASE_URL) //传入服务器地址
.build();
} else {
return retrofit;
}
}
private static final Interceptor LoggingInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Logger.t(TAG).i(String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Logger.t(TAG).i(String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
};
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!NetUtil.isConnected(App.getInstance())) {
request = request.newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)
.build();
Logger.t(TAG).w("no network");
}
Response originalResponse = chain.proceed(request);
if (NetUtil.isConnected(App.getInstance())) {
//有网的时候读接口上的@Headers里的配置,你可以在这里进行统一的设置
String cacheControl = request.cacheControl().toString();
return originalResponse.newBuilder()
.header("Cache-Control", cacheControl)
.removeHeader("Pragma")
.build();
} else {
return originalResponse.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=2419200")
.removeHeader("Pragma")
.build();
}
}
};
}
service代码
@Multipart
@POST("app/head_portrait_img")
Observable<String> uploadImage(@Part List<MultipartBody.Part> partList);
请求接口
private void upLoad(String fileName) {
List<String> pathList = getPathList();//此处是伪代码,获取多张待上传图片的地址列表
Request request = RetrofitUtil.getInstance().create(Request.class);
File file = new File(fileName);//filePath 图片地址
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM)//表单类型
.addFormDataPart("token", useNmae);//ParamKey.TOKEN 自定义参数key常量类,即参数名
//多张图片
for (int i = 0; i < pathList.size(); i++) {
File file = new File(pathList.get(i));//filePath 图片地址
RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
builder.addFormDataPart("imgfile"+i, file.getName(), imageBody);//"imgfile"+i 后台接收图片流的参数名
}
RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
builder.addFormDataPart("head_ico", file.getName(), imageBody);//imgfile 后台接收图片流的参数名
List<MultipartBody.Part> parts = builder.build().parts();
weiYunRequest.uploadImage(parts).subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ErrorMessge>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
//错误处理
Log.d("Throwableisr", e.toString() + "");
unsubscribe();
}
@Override
public void onNext(final ErrorMessge bean) {
//请求成功,这儿图片也上传成功
}
参考地址:(http://blog.csdn.net/itjianghuxiaoxiong/article/details/52135748)