本文介绍了使用OKHttp创建正确的MultipartBuilder Http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重新编码我的项目并使用okHttp代替Android中实现的默认HttpClient.

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

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

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

现在,我找到了一些有关如何创建和构建POST请求的示例.

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

现在是我的问题.我想创建一个保留几个数据(字符串,文件等)的RequestBody,但是我不能直接分配它们.

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

意味着RequestBuilder必须经过不同的循环才能添加数据.

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

OkHTTPs RequestBody似乎立即需要数据,如示例中所列 https://github.com/square/okhttp/wiki/Recipes

OkHTTPs RequestBody seems to need the data immediatly as listed in the examplehttps://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,则不会编译/运行.

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.

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

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

推荐答案

这使用okHttp3对我有用:

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

这篇关于使用OKHttp创建正确的MultipartBuilder Http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 22:39