使用Android SDK发布多部分请求

82

我尝试做一件我认为相对简单的事情:使用Android SDK将图像上传到服务器。我找到了很多示例代码:

http://groups.google.com/group/android-developers/browse_thread/thread/f9e17bbaf50c5fc/46145fcacd450e48

http://linklens.blogspot.com/2009/06/android-multipart-upload.html

但是两者对我都不起作用。我遇到的困惑是什么是真正需要进行多部分请求的东西。有没有最简单的方法来实现Android的多部分上传(上传图片)?

非常感谢任何帮助和建议!


你尝试过的方法有哪些问题? - Christopher Orr
1
哦,好多问题啊。目前正在将从照片选择器返回的照片URI传递到一个文件中,以便我可以将其附加到MultipartEntity上。但我甚至不确定这是否是构建多端口请求的正确方式。 - jpoz
这真的是非常老的内容。有人需要使用现代库来回答这个问题,或者至少发布可行的代码!自从这个问题被提出以来的十年间,有太多的东西已经被废弃,我很难找到甚至可以编译的东西。 - SMBiggs
12个回答

0
我可以推荐Ion库,它使用3个依赖项,你可以在以下两个网站找到这三个jar文件:
https://github.com/koush/ion#jars(ion和androidasync) https://code.google.com/p/google-gson/downloads/list (Gson)
try {
   Ion.with(this, "http://www.urlthatyouwant.com/post/page")
   .setMultipartParameter("field1", "This is field number 1")
   .setMultipartParameter("field2", "Field 2 is shorter")
   .setMultipartFile("imagefile",
        new File(Environment.getExternalStorageDirectory()+"/testfile.jpg"))
   .asString()
   .setCallback(new FutureCallback<String>() {
        @Override
        public void onCompleted(Exception e, String result) {
             System.out.println(result);
        }});
   } catch(Exception e) {
     // Do something about exceptions
        System.out.println("exception: " + e);
   }

这将异步运行,一旦收到响应,回调将在UI线程中执行。我强烈建议您前往https://github.com/koush/ion获取更多信息。


0

为了后人,我没有看到 okhttp 被提到。 相关帖子。

基本上,您可以使用 MultipartBody.Builder 构建请求体,并将其作为请求进行提交。

Kotlin 示例:

    val body = MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart(
                "file", 
                file.getName(),
                RequestBody.create(MediaType.parse("image/png"), file)
            )
            .addFormDataPart("timestamp", Date().time.toString())
            .build()

    val request = Request.Builder()
            .url(url)
            .post(body)
            .build()

    httpClient.newCall(request).enqueue(object : okhttp3.Callback {
        override fun onFailure(call: Call?, e: IOException?) {
            ...
        }

        override fun onResponse(call: Call?, response: Response?) {
            ...
        }
    })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接