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,"上傳失敗");
            }
        });



    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章