使用okhttp3+retrofit2+rxjava2上传头像

RetrofitInterface:
//https://www.zhaoapi.cn/file/upload
    @Multipart
    @POST("file/upload")
    Observable<PicturesBean> getPicturesBean(@Part("uid") RequestBody uid,@Part MultipartBody.Part file);

调用:此处需要图片的路径,如果是裁剪后的先保存起来(ImageUtil中有方法)

public void uploadPic(String uid,String path) {
        File file = new File(path);

        RequestBody uidBody = RequestBody.create(MediaType.parse("multipart/form-data"), uid);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));

        Observable<PicturesBean> picturesBean = retrofitInterface.getPicturesBean(uidBody,filePart);
        picturesBean.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PicturesBean>() {
                    @Override
                    public void onSubscribe(Disposable d) { }
                    @Override
                    public void onNext(PicturesBean picturesBean) {
                        getView().onSuccess(picturesBean,3);
                    }
                    @Override
                    public void onError(Throwable e) {
                        Log.e("myMessage", e.toString());
                    }
                    @Override
                    public void onComplete() { }
                });
    }

ImageUtil:

/**
 * 图片工具类
 * author:Created by WangZhiQiang on 2018/5/22.
 */
public class ImageUtil {
    /**
     * 保存bitmap到本地
     * @param bitmap
     * @return
     */
    public static void saveBitmap(Bitmap bitmap,String savePath) {
        File filePic;
        try {
            filePic = new File(savePath);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePic));
            //注意Bitmap.CompressFormat.PNG
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取相册图片路径
     * @param context
     * @param data
     * @return
     */
    public static String selectImage(Context context,Intent data){
        String path;
        if (data != null) {
            Uri uri = data.getData();
            if (!TextUtils.isEmpty(uri.getAuthority())) {
                Cursor cursor = context.getContentResolver().query(uri, new String[] { MediaStore.Images.Media.DATA },null, null, null);
                if (null == cursor) {
                    Toast.makeText(context, "图片没找到", Toast.LENGTH_SHORT).show();
                    return null;
                }
                cursor.moveToFirst();
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                cursor.close();
            } else {
                path = uri.getPath();
            }
        }else{
            Toast.makeText(context, "图片没找到", Toast.LENGTH_SHORT).show();
            return null;
        }
        return path;
    }
}

RetrofitUtil:

public class RetrofitUtil {
    private Retrofit retrofit;
    private static RetrofitUtil retrofitUtil;

    private RetrofitUtil() { }
    private RetrofitUtil(String baseUrl) {
        //第三方的日志拦截器
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLogger());
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //OKhttp3  设置拦截器打印日志
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
//                .addNetworkInterceptor(logInterceptor)
//                .addInterceptor(new LoggingInterceptor())//自定义拦截器
                .build();
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl) //设置网络请求的Url地址
                .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//支持RxJava2平台
                .client(okHttpClient)//OKhttp3添加到Retrofit
                .build();
    }
    //可指定baseUrl
    public static RetrofitUtil getInstance(String baseUrl){
        if (retrofitUtil==null){
            synchronized (RetrofitUtil.class){
                if (null==retrofitUtil){
                    retrofitUtil = new RetrofitUtil(baseUrl);
                }
            }
        }
        return retrofitUtil;
    }
    //默认的baseUrl
    public static RetrofitUtil getInstance(){
        if (null == retrofitUtil){
            return  getInstance("https://www.zhaoapi.cn/");
        }
        return retrofitUtil;
    }
    //获得Retrofit
    public Retrofit getRetrofit(){
        return retrofit;
    }
    //直接获得RetrofitInterface
    public RetrofitInterface getRetrofitInterface(){
        RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);
        return retrofitInterface;
    }
    //自定义拦截器
    public static class LoggingInterceptor implements Interceptor {
        @Override public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            //请求前--打印请求信息
            long t1 = System.nanoTime();
            Log.e("myMessage",String.format("Sending url %s \n %s \n\n%s \n\n %s",
                    request.url(), chain.connection(), request.headers(),request.body()));

            //网络请求
            okhttp3.Response response = chain.proceed(request);

            //网络响应后--打印响应信息
            long t2 = System.nanoTime();
            Log.e("myMessage",String.format("Received response for %s in %.1fms%n%s",
                    response.request().url(), (t2 - t1) / 1e6d, response.headers()));

            return response;
        }
    }
    //日志信息
    public static class HttpLogger implements HttpLoggingInterceptor.Logger {
        @Override
        public void log(String message) {
            Log.e("myMessage", message);
        }
    }
}
PicturesBean:
public class PicturesBean {
    /**
     * msg : 天呢!文件不能为空
     * code : 1
     */

    private String msg;
    private String code;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41673194/article/details/80415210