```

public class RetrofitUtil {

private static finalStringTAG="retrofit";

//TODO:修改主机地址

private static finalStringBASE_URL="服务器地址/";

private static final intDEFAULT_TIMEOUT=5;//请求时间

private staticRetrofitretrofit;

//实例化私有

privateWeiYunRetrofitUtil() {

}

public staticRetrofit getInstance() {

if(retrofit==null) {

ClearableCookieJar cookieJar =

newPersistentCookieJar(newSetCookieCache(),newSharedPrefsCookiePersistor(App.getInstance()));

OkHttpClient.Builder httpClientBuilder =newOkHttpClient.Builder();//okhttp创建,写入缓存机制,还有addInterceptor

httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);

File cacheFile =newFile(App.getInstance().getCacheDir(),"superman");

Cache cache =newCache(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 newRetrofit.Builder()//retrofit的创建。

.client(httpClientBuilder.build())

//传入okhttp

.addConverterFactory(newNullOnEmptyConverterFactory())

.addConverterFactory(GsonConverterFactory.create())//传入gson解析手段

.addCallAdapterFactory(RxJavaCallAdapterFactory.create())

//传入异步手段

.baseUrl(BASE_URL)//传入服务器地址

.build();

}else{

returnretrofit;

}

}

private static finalInterceptorLoggingInterceptor=newInterceptor() {

@Override

publicResponse intercept(Chain chain)throwsIOException {

Request request = chain.request();

longt1 = 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);

longt2 = System.nanoTime();

Logger.t(TAG).i(String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) /1e6d, response.headers()));

returnresponse;

}

};

private static finalInterceptorREWRITE_CACHE_CONTROL_INTERCEPTOR=newInterceptor() {

@Override

publicResponse intercept(Chain chain)throwsIOException {

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();

returnoriginalResponse.newBuilder()

.header("Cache-Control", cacheControl)

.removeHeader("Pragma")

.build();

}else{

returnoriginalResponse.newBuilder()

.header("Cache-Control","public, only-if-cached, max-stale=2419200")

.removeHeader("Pragma")

.build();

}

}

};

接口实现

public interface Request {

//    头像上传

@Multipart

@POST("app/head_portrait_img")

Observable uploadImage(@Part List partlist);

}

调用接口

MultipartBody.Builder builder =newMultipartBody.Builder()

.setType(MultipartBody.FORM)//表单类型

.addFormDataPart("user_id", uid)

.addFormDataPart("timespan", name)

.addFormDataPart("token", useNmae);//ParamKey.TOKEN 自定义参数key常量类,即参数名

RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);

builder.addFormDataPart("pic_upload", file.getName(), imageBody);//imgfile 后台接收图片流的参数名

builder.addFormDataPart("head_ico", file.getName(), imageBody);//imgfile 后台接收图片流的参数名

List parts = builder.build().parts();

weiYunRequest.uploadImage(parts).subscribeOn(Schedulers.io())

.unsubscribeOn(Schedulers.io())

.observeOn(AndroidSchedulers.mainThread())

.subscribe(newSubscriber() {

@Override

public voidonCompleted() {

}

@Override

public voidonError(Throwable e) {

ByAlert.alert("上传失败");

Log.d("Throwableisr", e.toString() +"");

unsubscribe();

Glide.with(PersonalActivity.this)

.load("")

.error(R.drawable.err_logo)

.bitmapTransform(newCropCircleTransformation(PersonalActivity.this))

.into(pereHead);

try{

closeProgressDialog();

}catch(Exception t) {

}

}

@Override

public voidonNext(finalErrorMessge bean) {

}

```