从Android发布文件到服务器 - MultipartEntityBuilder - HTTP

时间:2014-10-06 05:57:03

标签: android http file-upload multipart

我正在尝试从Android应用程序上传一些文件到我的服务器(通过HTTP POST),我在这里检查了很多问题,但无法让它工作。我希望有人可以帮助我:

我还在URL中包含了一些变量,以验证至少那些变量到达服务器(GET)。

    HttpClient httpClient = new DefaultHttpClient();
    String url="http://XXXXX.com/files/upload.php?flies=yes&eats=no&friend=yes";
    HttpPost httppost = new HttpPost(url);
    httppost.addHeader("Content-Type", "multipart/form-data");
    String content,response="";
    try {

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addTextBody("randomvar", "42");

        //add image file
        //String filename="eye.png";
        //InputStream is=mContext.getAssets().open(filename);
        //builder.addBinaryBody("image", is, ContentType.create("image/png"), filename);

        //add text XML file
        final File file = new File(mContext.getFilesDir() +"/"+"serverXML.xml");
        FileBody fb = new FileBody(file);
        builder.addPart("file", fb);
        httppost.setEntity(builder.build());


        response = EntityUtils.toString(httpClient.execute(httppost).getEntity(), "UTF-8");


        Log.i(TAG, "RESPONSE FROM SERVER: "+response);
    } catch (IOException e) {
        Log.i(TAG, "Exception: "+response);
        e.printStackTrace();
    }

这会运行并从服务器获得响应。以下是$ _GET,$ _POST,$ _FILES:

的vardump

enter image description here

我希望POST拥有文件和变量

在我的Eclipse Logcat中,我在使用MultiPartEntityBuilder后看到以下内容:

10-06 02:36:57.231: D/dalvikvm(15888): DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueParser;.INSTANCE
10-06 02:36:57.241: W/dalvikvm(15888): VFY: unable to resolve static field 5966 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueParser;
10-06 02:36:57.241: D/dalvikvm(15888): VFY: replacing opcode 0x62 at 0x001b
10-06 02:36:57.241: D/dalvikvm(15888): DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueFormatter;.INSTANCE
10-06 02:36:57.241: W/dalvikvm(15888): VFY: unable to resolve static field 5960 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueFormatter;

我想我已经正确地包含了所有必需的库:

enter image description here

修改

我能够解决这个问题,我的解决方案在下面的答案中描述

2 个答案:

答案 0 :(得分:5)

我很幸运能在Stackoverflow中找到一个Answer by Krystian来解决我的问题。

添加边界后,它开始工作。我不得不将它添加到HTTP Post

String boundary = "-------------" + System.currentTimeMillis();
httppost.setHeader("Content-type", "multipart/form-data; boundary="+boundary);

和实体

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setBoundary(boundary);

现在我收到了服务器中的所有内容:

10-06 13:16:06.977: I/UploadFileAsync(31506): RESPONSE FROM SERVER: Array
10-06 13:16:06.977: I/UploadFileAsync(31506): (
10-06 13:16:06.977: I/UploadFileAsync(31506):     [flies] => yes
10-06 13:16:06.977: I/UploadFileAsync(31506):     [eats] => no
10-06 13:16:06.977: I/UploadFileAsync(31506):     [friend] => yes
10-06 13:16:06.977: I/UploadFileAsync(31506): )
10-06 13:16:06.977: I/UploadFileAsync(31506): Array
10-06 13:16:06.977: I/UploadFileAsync(31506): (
10-06 13:16:06.977: I/UploadFileAsync(31506):     [randomvar] => 42
10-06 13:16:06.977: I/UploadFileAsync(31506):     [mystr] => blaka
10-06 13:16:06.977: I/UploadFileAsync(31506): )
10-06 13:16:06.977: I/UploadFileAsync(31506): Array
10-06 13:16:06.977: I/UploadFileAsync(31506): (
10-06 13:16:06.977: I/UploadFileAsync(31506):     [file] => Array
10-06 13:16:06.977: I/UploadFileAsync(31506):         (
10-06 13:16:06.977: I/UploadFileAsync(31506):             [name] => serverXML.xml
10-06 13:16:06.977: I/UploadFileAsync(31506):             [type] => application/octet-stream
10-06 13:16:06.977: I/UploadFileAsync(31506):             [tmp_name] => /tmp/phpdmEsn2
10-06 13:16:06.977: I/UploadFileAsync(31506):             [error] => 0
10-06 13:16:06.977: I/UploadFileAsync(31506):             [size] => 3548
10-06 13:16:06.977: I/UploadFileAsync(31506):         )
10-06 13:16:06.977: I/UploadFileAsync(31506): )

答案 1 :(得分:1)

你必须像这样工作

public void connectForMultipart() throws Exception {
    con = (HttpURLConnection) ( new URL(url)).openConnection();
    con.setRequestMethod("POST");
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setRequestProperty("Connection", "Keep-Alive");
    con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    con.connect();
    os = con.getOutputStream();
}

public void addFormPart(String paramName, String value) throws Exception {
    writeParamData(paramName, value);
}

public void addFilePart(String paramName, String fileName, byte[] data) throws Exception {
    os.write( (delimiter + boundary + "\r\n").getBytes());
    os.write( ("Content-Disposition: form-data; name=\"" + paramName +  "\"; filename=\"" + fileName + "\"\r\n"  ).getBytes());
    os.write( ("Content-Type: application/octet-stream\r\n"  ).getBytes());
    os.write( ("Content-Transfer-Encoding: binary\r\n"  ).getBytes());
    os.write("\r\n".getBytes());

    os.write(data);

    os.write("\r\n".getBytes());
}   
public void finishMultipart() throws Exception {
    os.write( (delimiter + boundary + delimiter + "\r\n").getBytes());
}

获取回复

httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);

BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));



String sResponse;
while ((sResponse = reader.readLine()) != null) 
 {
     s = s.append(sResponse);
 }

 if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
 {
     return s.toString();
 }else
 {
     return "{\"status\":\"false\",\"message\":\"Some error occurred\"}";
 }   
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

代替图像,您可以发送任何内容(在您的情况下为xml文件),您希望...如果它创建了一些heck然后 你应该将大文件分成小部分,然后尝试发送。并在服务器上加入这个小部分。

在我的情况下httpmime-4.2.1-1.jar仅在此代码中需要