Creating a proper MultipartBuilder Http Request with OKHttp

喜你入骨 提交于 2019-11-30 19:36:11

问题


ild like to recode my project and use okHttp instead of the default HttpClient implemented in Android.

I've downloaded the latest source of the okhttp-main release.

Now ive found some examples how to create and build a POST Request.

Now my Problem. I want to create a RequestBody which keep several Data (Strings, Files, whatever) but i can't assign them directly.

Means that the RequestBuilder must go through different Loops where it get it's data added.

OkHTTPs RequestBody seems to need the data immediatly as listed in the example https://github.com/square/okhttp/wiki/Recipes

When i want to try something like

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();

it fails because build() itself create the RequestBody. Before it's just a MultipartBuilder(). If i try to force the type to RequestBody it wont compile/run.

So, what is the proper way adding thos data after creating a MultiPartBuilder and add DATA and Strings?


回答1:


This worked for me using 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);



回答2:


Uploading file in multipart using OkHttp

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());
}



回答3:


I modified 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());
}

Start adding the formDataPart to builder and at end create RequestBody

RequestBody requestBody = builder.build();

you can perform above actions with

 compile 'com.squareup.okhttp3:okhttp:3.4.1'


来源:https://stackoverflow.com/questions/24306320/creating-a-proper-multipartbuilder-http-request-with-okhttp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!