如何 post 在 android 中将图像发送到服务器

How to post an image to server in android

如何上传图片到服务器? 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);
                    }
                });
            }
        });
    }

你好,以上答案完全正确并被接受,但这是将图像发布到服务器的最简单方法的另一种解决方案:-

在您的 android 项目中使用来自 andoid spring 框架的 rest api 只需创建新的自定义界面,如下所示:-

@Rest(rootUrl ="BASE_URL", converters = {ByteArrayHttpMessageConverter.class,
    FormHttpMessageConverter.class, StringHttpMessageConverter.class})
public interface CustomRest extends RestClientErrorHandling {

@Post("YourPostfixforUrl")
String _postImage(MultiValueMap<String, Object> multiValueMap);

}

使用以下代码创建您自己的 RestErrorHandler:-

@EBean
public class CustomRestErrorHandler implements RestErrorHandler
{
    @Override
    public void onRestClientExceptionThrown(NestedRuntimeException e)
    {
        Log.e("NestedRuntimeException ", "NestedRuntimeException :- " + e.toString());
    }
}

在你的 activity 调用下面的代码:-

 @AfterInject
public void afterInject() {
    MultiValueMap<String, Object> ObjectMultiValueMap = new LinkedMultiValueMap<>();
    ObjectMultiValueMap.add("yourImageKey", new FileSystemResource(new File("yourFilePath")));
    doInBackground(myrest, ObjectMultiValueMap);
}

@Background
public void doInBackground(Myrest myrest, MultiValueMap<String, Object> multiValueMap) {
    myrest.setRestErrorHandler(myErrorHandler);

}

您的 Gradle 将如下所示:-

def AAVersion = '3.3.2'    
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
apt "org.androidannotations:androidannotations:$AAVersion"
compile "org.androidannotations:androidannotations-api:$AAVersion"
compile 'org.springframework.android:spring-android-core:1.0.1.RELEASE'
compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'}

注意:- 你的activity必须是@Eactivity

--> 我猜 androidannotation+rest 是最好的节省时间和真诚优化代码片段的方法! 谢谢