如何将图像上传到服务器? MultiPArtEntity 和 MultiPartEntityBuilder 类在 API 级别 23 中均已弃用。我们可以使用 HTTPUrlConnection 或 volley 来完成此操作吗?
最佳答案
我建议你使用OkHttp。有关它的更多详细信息,您可以在以下位置找到:
OkHttp - An HTTP & SPDY client for Android and Java applications
请参阅我的基本示例代码,该代码将 PNG 文件从可绘制文件夹上传到远程 Web 服务。希望这有帮助!
...
mTextView = (TextView) findViewById(R.id.textView);
mHandler = new Handler(Looper.getMainLooper());
...
Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
if (drawable != null) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
final byte[] bitmapdata = stream.toByteArray();
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"file\"; filename=\"ic_launcher.png\""),
RequestBody.create(MEDIA_TYPE_PNG, bitmapdata))
.build();
final Request request = new Request.Builder()
.url("http://myserver/api/files")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Request request, final IOException e) {
Log.e(LOG_TAG, e.toString());
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
mTextView.setText(e.toString());
}
});
}
@Override
public void onResponse(Response response) throws IOException {
final String message = response.toString();
Log.i(LOG_TAG, message);
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
mTextView.setText(message);
}
});
}
});
}
关于http-post - 如何在android中将图像发布到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33932916/