使用OKHttp创建正确的MultipartBuilder Http请求

时间:2014-06-19 12:11:33

标签: android multipartform-data okhttp

ild喜欢重新编码我的项目并使用okHttp而不是Android中实现的默认HttpClient。

我已经下载了okhttp-main版本的最新资源。

现在我已经找到了一些如何创建和构建POST请求的例子。

现在我的问题。我想创建一个RequestBody,它保存几个数据(字符串,文件,等等),但我无法直接分配它们。

意味着RequestBuilder必须通过不同的循环来获取它的数据。

OkHTTPs RequestBody似乎需要立即按照示例中列出的数据 https://github.com/square/okhttp/wiki/Recipes

当我想尝试像

这样的东西时
RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM);

for (Object aMData : dataClass.getData().entrySet()) {
            Map.Entry mapEntry = (Map.Entry) aMData;
            String keyValue = (String) mapEntry.getKey();
            String value = (String) mapEntry.getValue();
            requestBody.addPart(keyValue, value);
}


for (DataPackage dataPackage : dataClass.getDataPackages()) {
            requestBody.addPart("upfile[]", dataPackage.getFile());
}

requestBody.build();

它失败,因为build()本身创建了RequestBody。在它之前只是一个MultipartBuilder()。如果我尝试将类型强制为RequestBody,它将不会编译/运行。

那么,在创建MultiPartBuilder并添加DATA和字符串后添加数据的正确方法是什么?

3 个答案:

答案 0 :(得分:2)

这对我使用okHttp3:

            OkHttpClient client = new OkHttpClient();
            File file = new File(payload);

            RequestBody formBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", "image.jpg",
                            RequestBody.create(MediaType.parse("image/jpg"), file))

                    .build();

            Request request = new Request.Builder().url(url).post(formBody).build();

            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

答案 1 :(得分:1)

使用OkHttp

在multipart中上传文件
private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
  // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
  RequestBody requestBody = new MultipartBuilder()
      .type(MultipartBuilder.FORM)
      .addPart(
          Headers.of("Content-Disposition", "form-data; name=\"title\""),
          RequestBody.create(null, "Square Logo"))
      .addPart(
          Headers.of("Content-Disposition", "form-data; name=\"image\""),
          RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
      .build();

  Request request = new Request.Builder()
      .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
      .url("https://api.imgur.com/3/image")
      .post(requestBody)
      .build();

  Response response = client.newCall(request).execute();
  if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

  System.out.println(response.body().string());
}

答案 2 :(得分:1)

我修改了Dr. Enemy's answer

 MultipartBody.Builder builder =new MultipartBody.Builder().setType(MultipartBody.FORM);

for (Object aMData : dataClass.getData().entrySet()) {
        Map.Entry mapEntry = (Map.Entry) aMData;
        String keyValue = (String) mapEntry.getKey();
        String value = (String) mapEntry.getValue();
        builder.addPart(keyValue, value);
}

for (DataPackage dataPackage : dataClass.getDataPackages()) {
        builder.addPart("upfile[]", dataPackage.getFile());
}

开始将formDataPart添加到构建器,最后创建RequestBody

RequestBody requestBody = builder.build();

您可以使用

执行上述操作
 compile 'com.squareup.okhttp3:okhttp:3.4.1'