Retrofit+Rxjava,post请求方式上传头像(从相册获取)

最开始要添加所需要的依赖
在项目的build文件中,(最外面)

ext {
    // Sdk and tools
    minSdkVersion = 19
    targetSdkVersion = 26
    compileSdkVersion = 26
    buildToolsVersion = '26.0.2'
    //support版本
    supportVersion = '27.1.0'
    constraintLayout = '1.0.2'
    junit = '4.12'
    testRunner = '1.0.1'
    espressoCore = '3.0.1'

    interceptor = "3.11.0"
    retrofit = '2.3.0'
    converterGson = '2.3.0'
    rxandroid = '1.2.1'
    rxjava = '1.3.0'
    rxbus = '1.0.6'
    adapterRxjava = '2.0.2'
}

在当前module中

implementation "com.squareup.okhttp3:logging-interceptor:$rootProject.interceptor"
    implementation "com.squareup.retrofit2:retrofit:$rootProject.retrofit"
    implementation "com.squareup.retrofit2:converter-gson:$rootProject.converterGson"
    implementation "io.reactivex:rxandroid:$rootProject.rxandroid"
    implementation "io.reactivex:rxjava:$rootProject.rxjava"
    implementation "com.hwangjr.rxbus:rxbus:$rootProject.rxbus"
    implementation "com.squareup.retrofit2:adapter-rxjava:$rootProject.adapterRxjava"
    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

在api里的接口

public interface MyApiService {
@POST
    Observable postHeader(@Url String url, @HeaderMap HashMap header, @Body MultipartBody file);
}

自己封装的一个工具类

public class OkHttpUtil {


    private final OkHttpClient okHttpClient;
    private final MyApiService myApiService;

    public static OkHttpUtil getInterface() {
        return OkHttp.okHttpUtil;
    }
//静态内部类单例模式
    static class OkHttp {
        private static final OkHttpUtil okHttpUtil = new OkHttpUtil();
    }

    private OkHttpUtil() {
    //OkHttp和retrofit的配置
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .callTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(okHttpClient)
                .baseUrl(Contacts.BASE_PORT)
                .build();
        myApiService = retrofit.create(MyApiService.class);
    }


    public OkHttpUtil postHeader(String url, HashMap header, String path) {
        if (header == null) {
            header = new HashMap<>();
        }
//通过一个图片路径,转换类型
        File file = new File(path);
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/octet-stream"), file);
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart("image", file.getName(), requestBody);
//调用方法
        myApiService.postHeader(url, header, builder.build())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
        return OkHttpUtil.getInterface();
    }

//观察者
    private Observer observer = new Observer() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            if (okHttpFace != null) {
                okHttpFace.onError(e.getMessage());
            }
        }

        @Override
        public void onNext(ResponseBody responseBody) {
            if (okHttpFace != null) {
                try {
                    okHttpFace.onSuccess(responseBody.string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    };

//自定义接口回调
    public interface OkHttpFace {
        void onSuccess(String data);

        void onError(String error);
    }

    private OkHttpFace okHttpFace;

    public void setOkHttpFace(OkHttpFace okHttpFace) {
        this.okHttpFace = okHttpFace;
    }
}

打开图库

Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 200);

成功的返回

    Uri uri = data.getData();
    sendMyProfileImage.setImageURI(uri);//给控件设置图片
    String[] filePathColumn = {MediaStore.Images.Media.DATA};
    Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
    cursor.moveToFirst();
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    //picturePath就是图片在储存卡所在的位置
    String picturePath = cursor.getString(columnIndex);
    cursor.close();
    //调用方法
    OkHttpUtil.getInterface().postHeader(Contacts.PROFILE_HEADER, header, picturePath).setOkHttpFace(new OkHttpUtil.OkHttpFace() {
                @Override
                public void onSuccess(String data) {
                    //接口的成功返回
                }

                @Override
                public void onError(String error) {
                   //失败返回
                }
            });

相机拍照后上传,其它的都一样只需要将调用相机后的成功返回的类型改变一下

bitmap转uri      Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null,null)); 

你可能感兴趣的:(功能总结)