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

来源:互联网 发布:迪姆软件 编辑:程序博客网 时间:2024/06/06 11:01

功能需求

根据下面的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,"上传失败");            }        });    }