使用okHttp上传图片 [英] Image upload using okHttp
本文介绍了使用okHttp上传图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 okhttp 上传图片,但我找不到用于 Post Image 的 MultipartBuilder.我可以用什么来代替它.
i want to upload image using okhttp but i am not able to find MultipartBuilder for Post Image.What can i use instead of this.
这是我的代码
public static JSONObject uploadImage(File file) {
try {
final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
RequestBody req = new MultipartBuilder().setType(MultipartBody.FORM)
.addFormDataPart("userid", "8457851245")
.addFormDataPart(
"userfile",
"profile.png",
RequestBody.create(MEDIA_TYPE_PNG, file)
)
.build();
Request request = new Request.Builder()
.url("url")
.post(req)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
Log.d("response", "uploadImage:" + response.body().string());
return new JSONObject(response.body().string());
} catch (UnknownHostException | UnsupportedEncodingException e) {
Log.e(TAG, "Error: " + e.getLocalizedMessage());
} catch (Exception e) {
Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
}
return null;
}
提前致谢.
推荐答案
你需要使用
new MultipartBody.Builder()
代替
new MultipartBuilder()
它的工作原理
这篇关于使用okHttp上传图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文