Retrofit实现文件上传/图片上传/Json字符串上传

上传图片

配置依赖

ext {
    versionName ='1.0.0'
    androidutilsVersion = '1.0.6'
    appcompatVersion = '27.1.1'
    butterknifeVersion = '8.8.1'
    retrofitVersion = '2.4.0'
    logginginterceptor = '3.9.1'
    rxjavaVersion = '2.1.14'
    rxandroidVersion = "2.0.2"
    rxlifecycle='2.1.0'
}
dependencies {
    implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
    implementation "com.squareup.okhttp3:logging-interceptor:$logginginterceptor"
    implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion"
    implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion"
    implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofitVersion"
    implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:latest.integration'
    implementation "io.reactivex.rxjava2:rxandroid:$rxandroidVersion"
    implementation "io.reactivex.rxjava2:rxjava:$rxjavaVersion"
}

API服务类:

public interface ApiStores {
 @Multipart
    @POST("core/wechatpublic/upload")
    Observable uploadImage(@Part MultipartBody.Part file);
}

使用:

private void uploadFileThree() {
        //服务器地址
        String servicePath = "http://47.103.47.46:9762/";
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(servicePath)
                .build();
        ApiStores apiStores = retrofit.create(ApiStores.class);
        //拼接参数
        RequestBody requestBody = null;
        //测试使用sd卡的图片
        String imgPath = Environment.getExternalStorageDirectory().getPath() + "/[email protected]";
        File file = new File(imgPath);
        requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        Observable observable = apiStores.uploadFeedbackTwo(body);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                //只需要关心onNext的消息和Throwable错误
                .subscribe(new Consumer() {
                    @Override
                    public void accept(String s) throws Exception {
//                        LogUtils.d("onNext=上传成功" + s);

                    }
                }, new Consumer() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
//                        LogUtils.d("throwable=" + throwable.getMessage());
                    }
                });
    }

 

上传Json

@POST("/uploadJson")
Observable uploadjson(
        @Body RequestBody jsonBody);

upLoadJson 也可以具体指明Content-Type 为 “application/json”格式的

具体组装我们的RequestBody则可以这样:

 RequestBody body= 
RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonString);

接着可以这样调用:

// 执行请求
Call call = service.uploadJson(description, body);
call.enqueue(new Callback() {
    @Override
    public void onResponse(Call call,
                           Response response) {
        Log.v("Upload", "success");
    }

    @Override
    public void onFailure(Call call, Throwable t) {
        Log.e("Upload error:", t.getMessage());
    }
});

 

至于服务器返回什么类型的model, 开发者可以自定义 譬如你可以把APi 中的 ResponseBody 指定为你自己的javaBean,当然上层构建Callback的时候也必须是 Call

@POST("/uploadJson")
Observable uploadjson(
        @Body RequestBody jsonBody);

参考:http://blog.csdn.net/sk719887916/article/details/51755427

你可能感兴趣的:(retrofit)