【发布时间】:2016-09-03 16:01:58
【问题描述】:
我正在使用 OKhttp 进行网络请求。试图将图像上传到服务器。这是我尝试过的方法,但它不起作用。我做错了什么?
client = new OkHttpClient.Builder()
.build();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("", "",
RequestBody.create(MediaType.parse("image/*"), encodedImage))
.build();
Request request = new Request.Builder()
.url(serverUrl)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
}
【问题讨论】:
-
“但它不工作”:它是如何“不工作”的?碰撞?无连接?你必须更详细,如果有崩溃,添加logcat
-
如果您想更快地完成工作,请改用Volley。如果您真的想获得帮助,请提供更多详细信息,例如 logcat。
-
为什么要对图片进行base64编码?
-
对表单数据部分名称使用空字符串也可能是一个错误。
标签: android http-post image-uploading okhttp