Bmob rxjava+retrofit、postman 上传图片

注意:Application id 和 rest api key需要填上自己的对象项目的

Rxjava Retrofit 主要代码实现

public interface ApiService {

    @POST("2/files/myPicture.jpg")
    Observable upload(@Body RequestBody img);

}

protected void upLoad(File file) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(
                        new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request()
                                .newBuilder()
                                .addHeader("X-Bmob-Application-Id", YOURS)
                                .addHeader("X-Bmob-REST-API-Key", YOURS)
                                .addHeader("Content-Type", "image/jpeg")
                                .build();
                        return chain.proceed(request);
                    }
                })
                .build();

        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
        new Retrofit.Builder()
                .baseUrl("https://api.bmob.cn/")
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
                .create(ApiService.class)
                .upload(requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e(TAG, "onSubscribe: " + d);
                    }

                    @Override
                    public void onNext(ResponseBean value) {
                        Log.e(TAG, "onNext: " + new Gson().toJson(value));
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

Postman上传图片

Bmob rxjava+retrofit、postman 上传图片_第1张图片
Bmob rxjava+retrofit、postman 上传图片_第2张图片

如postman上传图片失败可以尝试着方法 http://www.jianshu.com/p/4e03758a9d13

项目地址 https://github.com/androidHRTZ/BmobUpLoadImg.git

转载请在开头注明作者详细信息和本文出处 谢谢!

你可能感兴趣的:(Bmob rxjava+retrofit、postman 上传图片)