文件上传时的Retrofit2响应

时间:2017-07-13 07:40:10

标签: android retrofit okhttp

我想在myserver上传zip文件。我正在使用Retrofit2。我使用了以下代码。

private void uploadFile() {
    // create upload service client
    FileUploadService service =
            ServiceGenerator.createService(FileUploadService.class);

    File file = uploadFile;
    RequestBody requestFile =
            RequestBody.create(
                    MediaType.parse("application/x-www-form-‌urlencoded"),
                    file
            );

    MultipartBody.Part body =
            MultipartBody.Part.createFormData("fileUpload", file.getName(), requestFile);

    String descriptionString = "hello, this is description speaking";
    RequestBody description =
            RequestBody.create(
                    okhttp3.MultipartBody.FORM, descriptionString);

    Call<JSONObject> call = service.upload(description, body);
    call.enqueue(new Callback<JSONObject>() {
        @Override
        public void onResponse(Call<JSONObject> call,
                               Response<JSONObject> response) {
            System.out.println("UploadFragment.onResponse " + response);
            Log.v("Upload", "success");
        }

        @Override
        public void onFailure(Call<JSONObject> call, Throwable t) {
            Log.d("Upload error:", t.getCause().toString());
        }
    });
}

我的上传服务就像。

public interface FileUploadService {

@Multipart
@POST("myurl")
Call<JSONObject> upload(
        @Part("description") RequestBody description,
        @Part MultipartBody.Part file
);

}

问题当我上传文件时,我得到回复 {protocol = http / 1.1,code = 200,message = OK,url = http://myUrl 。 这不是我的服务器返回的响应。如何获得我的服务器响应?

1 个答案:

答案 0 :(得分:1)

它的改造响应。你会得到你的反应。

response.body().toString();

使用此

System.out.println("UploadFragment.onResponse " + response.body().toString());

我希望这会对你有所帮助。