如何使用retrofit2发送POST请求,其中一个表单数据字段是文件?

时间:2016-07-19 15:08:53

标签: android post retrofit2

使用retrofit2我想向我的API发出png上传请求。它必须是POST请求,png作为表单数据字段“img”传递。我使用Postman测试了我的API,一切正常,但现在我想使用retrofit2从Android应用程序发出此请求。这个图书馆甚至能够提出这样的要求吗?

enter image description here

2 个答案:

答案 0 :(得分:1)

上传图片:

File file = new File("/storage/emulated/0/Pictures/MyApp/test.jpg");

RequestBody requestBody = new MultipartBuilder()
                            .type(MultipartBuilder.FORM)
                            .addPart(Headers.of("Content-Disposition", 
                                     "form-data; name=\"image\";filename=\"" 
                                     + file.getName() + "\""),
                              RequestBody.create(MEDIA_TYPE_JPG, file))
                            .build();

// Todo: replace with your own interface e.g. apiClient
Call<ResponseBody> call = apiClient.uploadImage(requestBody);

call.enqueue(new Callback<ResponseBody>() {

    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        Log.v("Upload", "success");
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        Log.e("Upload error:", t.getMessage());
   }
});

定义了示例接口和必需的端点方法:

public interface ApiClient {
    @Multipart
    @POST("/content")
    Call<ResponseBody> uploadImage(@Part("image") RequestBody image);
}

答案 1 :(得分:0)

可能是你可以尝试Fast Android Networking库,因为它是简单快速的android网络库。我创建了这个基于OKHttp构建的库,它具有比Retrofit更多的功能和自定义。

你的gradle文件中的

添加依赖

编译&#39; com.amitshekhar.android:android-networking:0.0.1&#39;

    File file = new File(imagePath);
    AndroidNetworking.upload(url)
                     .addMultipartFile("img",file) 
                     .setTag("uploadTest")
                     .setPriority(Priority.HIGH)
                     .build()
                     .setUploadProgressListener(new UploadProgressListener() {
                        @Override
                        public void onProgress(long bytesUploaded, long totalBytes) {
                        // do anything with progress 
                        }
                     })
                     .getAsJSONObject(new JSONObjectRequestListener() {
                        @Override
                        public void onResponse(JSONObject response) {
                        // do anything with response                
                        }
                        @Override
                        public void onError(ANError error) {
                        // handle error 
                        }
                     }); 
}