使用Retrofit+RxJava上传文件

最近做了一个上传头像的demo,下面进行使用和介绍的记录

我的图片格式是Bitmap格式,所以这里要转换成文件

//Bitmap转文件
    public File getFile(Bitmap bmp) {
        //Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        //getApplicationContext 更改为 getContext
        String defaultPath = getApplicationContext().getFilesDir()
                .getAbsolutePath() + "/defaultGoodInfo";
        File file = new File(defaultPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String defaultImgPath = defaultPath + "/messageImg.jpg";
        file = new File(defaultImgPath);
        try {
            file.createNewFile();
            FileOutputStream fOut = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 20, fOut);
            fOut.flush();
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

下面是Retrofit的接口

@Multipart
    @POST("file/upload")
    Observable postUpLodding(@Query("uid") int uid , @Part MultipartBody.Part file);

工具类

public class RetrofitUtil {
    private static volatile RetrofitUtil sRetrofitUtil;
    private final OkHttpClient mHttpClient;

    private RetrofitUtil() {
        mHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    //实例化
    public static RetrofitUtil getInstance(){
        if(sRetrofitUtil == null){
            synchronized (RetrofitUtil.class){
                if(sRetrofitUtil == null){
                    sRetrofitUtil = new RetrofitUtil();
                }
            }
        }
        return sRetrofitUtil;
    }

    //方法
    public Observable doPost(String url, File file){

        //设置图片格式
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpg"), file);
        //设置一个file文件
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        RetrofitServer retrofitServer = new Retrofit.Builder()
                .client(mHttpClient)
                .baseUrl(url)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build().create(RetrofitServer.class);

        return  retrofitServer.postUpLodding(71,body).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }
}

获取数据的方法,参考即可

//转成文件格式
        File file = getFile(bitmap);

        RetrofitUtil instance = RetrofitUtil.getInstance();
        instance.doPost(CantroUrl.BASE_URL, file).subscribe(new Observer() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(NetWork s) {
                if("0".equals(s.getCode())){
                    Toast.makeText(MainActivity.this, "头像上传成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MainActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {

            }
        });

但是写完后发现会报一个错误

java.net.SocketException: sendto failed: ECONNRESET (Connection reset by peer)

解决,在Activity中的onCreate声明周期中加入

if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

你可能感兴趣的:(网络)