如何在Android Okhttp框架以文件形式上传图片?网友“听海”写了这段代码,昌晖仪表在此分享给大家。
以Post为例
public Observable<String> postImageview(final String url, final MultipartBody requestBody){
//创建被观察者
Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>(){
@Override
public void call(Subscriber<? super String> subscriber) {
final Subscriber mSubscriber=subscriber;
//没有取消订阅的时候
if(!mSubscriber.isUnsubscribed()){
//构建post请求
Request request=null;
String cookie=CliniciansApplication.getOkhttpCookie();
if(!BooleanUtils.isEmpty(cookie)){
request=new Request.Builder()
.addHeader("cookie",cookie)
.url(url)
.post(requestBody)
.build();
}else{
request=new Request.Builder()
.url(url)
.post(requestBody)
.build();
}
if(mOkHttpClient!=null){
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//通知订阅者的错误信息
mSubscriber.onError(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(null!=response){//response 不为空
if(response.isSuccessful()){//response 请求成功
//通知订阅者的成功信息
mSubscriber.onNext(response.body().string());
}else{//response 请求失败
//通知订阅者的错误信息
IOException IOExceptionx=new IOException();
mSubscriber.onError(IOExceptionx);
}
}else{//response 为空
//通知订阅者的错误信息
IOException IOExceptionx=new IOException();
mSubscriber.onError(IOExceptionx);
}
//通知完毕
mSubscriber.onCompleted();
}
});
}
}
}
});
return observable;
}
调用
private void uploadAva(final String posturl,final File file,final String path){
if((null!=mRxAndroidOkhttp)&&(null!=file)){
showProgressDialogs();
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
builder.addFormDataPart("files", file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
builder.addFormDataPart("sePath","avatar");
MultipartBody requestBody = builder.build();
//observable定义被观察者
mObservable=mRxAndroidOkhttp.postImageview(posturl,requestBody);
if(null!=mObservable){
//定义观察者
Subscriber<String> mSubscriber=new Subscriber<String>(){
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
dismissProgressDialogs();
toast.showToast(StringConstant.errorstate1);
}
@Override
public void onNext(String s) {
parseAva(s,path);
}
};
/**
* 订阅者关联被观察者
* Schedulers.io()说明是输入输出的计划任务
* AndroidSchedulers.mainThread()说明订阅者是中ui主线程中执行
* */
mObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(mSubscriber);
}
}
}