迁移MultipartBody请求以进行改造2

时间:2016-12-09 11:02:19

标签: android retrofit2

我正在使用OkHttpClientIntentService以及我拥有的代码(并且它正在运行)是:

RequestBody rBody =  = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(KEY, key)
                .addFormDataPart(DESCRIPTION, description)
                .addPart(RequestBody.create(MediaType.parse(IMAGE_TYPE),
                        imageFile))
                .build();

    Request uploadRequest = new Request.Builder()
            .url(url)
            .post(rBody)
            .addHeader(CONTENT_TYPE, MEDIATYPE)
            .build();

我在改装2中尝试的是:

UploadService文件:

@Multipart
@POST("new_post")
Call<ImageResponse> uploadImage(@Header("Content-Type") String contentType,
                    @Part("image") RequestBody imageRequestBody,
                    @Part("key") RequestBody apiKeyRequestBody, 
                    @Part("description") RequestBody descriptionRequestBody);

请求:

    uploadImageService.uploadImage(MEDIATYPE, 
            createRequestBodyForImage(uriPath),
            createRequestBodyForApiKey(),
            createRequestBodyForDescription(description))
            .enqueue(new Callback<Void>() {
            // success/failure code here

以及创建RequestBody的函数是:

private RequestBody createRequestBodyForImage(String uriPath) {
    File file = new File(uriPath);

    return RequestBody.create(MediaType.parse("image/jpeg"), file);
}

 private RequestBody createRequestBodyForApiKey() {
    JSONObject jsonObject = null;
    try {
        jsonObject = new JSONObject()
                .put("key", Constants.API_KEY);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return RequestBody.create(MediaType.parse("application/json"), jsonObject.toString());
}


// method for the description is same as above for api key 

事情是,我以改进的方式作为回应:&#34;错误的api密钥&#34;。 由于该密钥与我IntentService + OkHttpClient使用的密钥相同,我的请求是否有问题?

1 个答案:

答案 0 :(得分:1)

在界面

        @Multipart
            @POST("forms/submit")
            Call<ResponseModal> sendRequest(
                    @Part("json")
                            RequestBody body,

                    @PartMap()
                            Map<String, RequestBody> mapFileAndName);

将所有图像放入HashMap

RequestBody reqFile = RequestBody.create(MediaType.parse("image/jpg"), new File("/sdcard/file.jpg"));
 HashMap<String, RequestBody> map = new HashMap<>();
   map.put(key + "\"; filename=\"" + key + ".jpg", reqFile);

将所有参数设置为Hasmap格式

RequestBody json = createPartFromString(jsonString);

现在像这样调用api

  Call<ResponseModal> call = apiInterface.sendRequest(json, map);