http-post - 如何在android中将图像发布到服务器

标签 http-post android-volley httpurlconnection image-uploading multipart

如何将图像上传到服务器? 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/

相关文章:

python - 如何向 Python REST 请求添加基本身份验证?

php - 响应方法在 php 脚本中不能正常工作

android - 如何运行 Volley 测试?

java - 使用 Volley 简单请求时的未知类

java - 检查链接的 URL 状态代码时无法将 HttpResponseCode 错误解析为类型

go - 如何设置和解析正文请求中的时间?

c# - 如何在 asp.net 应用程序中从 jquery 设置 HttpPost 端点

android - java.lang.OutOfMemoryError : Could not allocate JNI Env 错误

java - 如何使用 HTTPURLConnection 和 put 方法创建目录。它总是创建一个文件而不是目录

android - 登录网站