android开发:使用Retrofit2框架,如何上传图片+json参数?

功能需求

根据下面的post请求参数,用retrofit2框架接口请求

  1. 请求地址
    http://{domain}/rest/services/file
  2. 请求方法
    POST
  3. 请求数据
请求体数据是否必填说明
json传文件参数,包含文件名和文件上传保存的路径
file文件对象

json数据格式如下:

{
"name": "", // 文件名称
"path": "" // 文件上传保存的路径,路径以“/”开始写起,路径最后无需再加“/”。
}

4.响应状态码

请求体数据是否必填。
Http状态码说明
200上传文件成功。
400上传文件失败或服务端错误。

实现代码

/**
 * 请求网络的API接口类
 * Created by zzf on 17/10/08.
 */
public interface ApiService {


@Multipart
    @POST("/rest/services/file")
    Call<BaseResponse<String>> uploadFileWithRequestBody(@Part("json") RequestBody jsonBody,
                                                  @Part MultipartBody.Part file);
}
public class RetrofitUtil {



    private static RetrofitUtil mInstance;
    private Retrofit retrofit;

    public RetrofitUtil(){

    }

    public static RetrofitUtil getInstance(){
        if (mInstance == null){
            synchronized (RetrofitUtil.class){
                mInstance = new RetrofitUtil();
            }
        }
        return mInstance;
    }


    /**
     * 自定义异常,当接口返回的{@link Response#code}不为{@link # OK}时,需要跑出此异常
     * eg:登陆时验证码错误;参数为传递等
     */
    public static class APIException extends Exception {
        public String code;
        public String message;

        public APIException(String code, String message) {
            this.code = code;
            this.message = message;
        }

        @Override
        public String getMessage() {
            return message;
        }
    }


    public  <T>T createRetrofitService(final Class<T> service,String baseUrl) {

        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .client(getOkHttpClient())//指定网络执行器
                    .addConverterFactory(GsonConverterFactory.create())//指定 Gson 作为解析Json数据的Converter
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//指定使用RxJava 作为CallAdapter
                    .baseUrl(baseUrl)
                    .build();

        }


        return retrofit.create(service);
    }
    public  OkHttpClient getOkHttpClient() {
        //日志显示级别 分为4类:NONE、BASIC、HEADERS、BODY。
        HttpLoggingInterceptor.Level level= HttpLoggingInterceptor.Level.BODY;
        //新建log拦截器
        HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.d("zcb","OkHttp====Message:"+message);
            }
        });
        loggingInterceptor.setLevel(level);
        //定制OkHttp
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient
                .Builder();
        //OkHttp进行添加拦截器loggingInterceptor
       // httpClientBuilder.addInterceptor(new HeaderInterceptor());
        httpClientBuilder.addInterceptor(loggingInterceptor);



        return httpClientBuilder.build();
    }


}
/**
 * Created by ljd on 3/25/16.
 */
public class ApiHelper extends RetrofitUtil {


    private ApiService apiService;
    private static ApiHelper mInstance;
    public static MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
    private final int pageSize = 10;
    /**
     * 服务器地址
     */
    private static final String API_BASE = Constants.API_BASE;

    public ApiService getApiService() {
        if (apiService == null) {
            apiService = createRetrofitService(ApiService.class,API_BASE);
        }
        return apiService;
    }

    private static class SingleHolder{

    }
    public static ApiHelper getInstance(){
        if (mInstance == null){
            synchronized (ApiHelper.class){
                mInstance = new ApiHelper();
            }
        }
        return mInstance;
    }
}

测试代码

public void upLoadPicToNet(String PictureUrl) {
        File file = new File(PictureUrl);
        String path ="/image/desk/product";
        Gson gson = new Gson();
        JsonObject jObj = new JsonObject();
        jObj.addProperty("name","20171108105505.jpg");
        jObj.addProperty("path",path);

        RequestBody bodyjson = RequestBody.create(ApiHelper.mediaType, gson.toJson(jObj));
        final RequestBody requestFile =
                RequestBody.create(MediaType.parse("image/jpg"), file);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("file", file.getName(), requestFile);

        Call<BaseResponse<String>> baseResponseCall =
                ApiHelper.getInstance().getApiService().uploadFileWithRequestBody(bodyjson, body);

        baseResponseCall.enqueue(new Callback<BaseResponse<String>>() {
            @Override
            public void onResponse(Call<BaseResponse<String>> call, Response<BaseResponse<String>> response) {
                if(response.isSuccessful()){


                    Log.i(TAG,"上传成功啦"+response.toString());
                }else {
                    Log.i(TAG,"上传失败啦");

                }
            }

            @Override
            public void onFailure(Call<BaseResponse<String>> call, Throwable t) {
                Log.e(TAG,"上传失败");
            }
        });



    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值