Android Multipart上传

zch*_*odd 10 android multipart http-status-code-404

作为我的Android应用程序的一部分,我想上传要远程存储的位图.我有简单的HTTP GET和POST通信工作完美,但有关如何进行多部分POST的文档似乎与独角兽一样罕见.

此外,我想直接从内存传输图像,而不是使用文件.在下面的示例代码中,我从一个文件中获取一个字节数组,以便稍后使用HttpClient和MultipartEntity.

    File input = new File("climb.jpg");
    byte[] data = new byte[(int)input.length()];
    FileInputStream fis = new FileInputStream(input);
    fis.read(data);

    ByteArrayPartSource baps = new ByteArrayPartSource(input.getName(), data);
Run Code Online (Sandbox Code Playgroud)

这一切对我来说都是相当清楚的,除了我不能为我的生活找到从哪里得到这个ByteArrayPartSource.我已链接到httpclient和httpmime JAR文件,但没有骰子.我听说HttpClient 3.x和4.x之间的包结构发生了巨大的变化.

是否有人在Android中使用此ByteArrayPartSource,他们是如何导入的?

在浏览文档并搜索互联网之后,我想出了一些符合我需求的东西.要创建一个多部分请求,例如表单POST,以下代码为我做了诀窍:

    File input = new File("climb.jpg");

    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:3000/routes");
    MultipartEntity multi = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    String line;

    multi.addPart("name", new StringBody("test"));
    multi.addPart("grade", new StringBody("test"));
    multi.addPart("quality", new StringBody("test"));
    multi.addPart("latitude", new StringBody("40.74"));
    multi.addPart("longitude", new StringBody("40.74"));
    multi.addPart("photo", new FileBody(input));
    post.setEntity(multi);

    HttpResponse resp = client.execute(post);
Run Code Online (Sandbox Code Playgroud)

HTTPMultipartMode.BROWSER_COMPATIBLE位非常重要.感谢Radomir关于此的博客.

non*_*ont 2

尝试这个:

 HttpClient httpClient = new DefaultHttpClient() ;

 HttpPost httpPost = new HttpPost("http://example.com");
 MultipartEntity entity = new MultipartEntity();     
 entity.addPart("file", new FileBody(file));
 httpPost.setEntity(entity );
 HttpResponse response = null;

 try {
     response = httpClient.execute(httpPost);
 } catch (ClientProtocolException e) {
     Log.e("ClientProtocolException : "+e, e.getMessage());         
 } catch (IOException e) {
     Log.e("IOException : "+e, e.getMessage());

 } 
Run Code Online (Sandbox Code Playgroud)