上传文件Android org.apache.http.entity.mime.MultipartEntity:错误请求错误

时间:2013-10-08 15:45:39

标签: java android

以下代码提供错误请求错误,代码中的任何解决方案或错误。

MultipartEntity entityPost = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

entityPost.addPart("data_1", new StringBody(String.valueOf(feedbackId), Charset.forName("UTF-8")));         
entityPost.addPart("file_1", new FileBody(__file));

HttpPost httppost = new HttpPost("http://www.example.com/webservice.asmx/method");
httppost.setEntity(entityPost);
httppost.setHeader("Content-Type", "multipart/form-data");

HttpResponse __response = HttpManager.httpClient().execute(httppost);

WebService的:

public String method() {    
    try {   
        System.Web.HttpContext postContext = System.Web.HttpContext.Current;

        string data = postContext.Request.Form["data_1"].ToString();

        System.Web.HttpFileCollection files = postContext.Request.Files;        
        System.Web.HttpPostedFile = files[0];

        //etc etc

    } catch (Exception ex) {
        //
    }
}

错误:

org.apache.http.client.HttpResponseException: Bad Request

提前谢谢

1 个答案:

答案 0 :(得分:0)

如Satya Komatineni,Dave MacLean,Sayed Y. Hashimi的Book Pro Android 3中所述。 添加了外部库:

Commons IO :http // commons.apache.org / io /

Mime4j :http // james.apache.org / mime4j /

HttpMime :http // hc.apache.org / downloads.cgi(在HttpClient内)

使用之前创建的相同Web服务可以正常工作。

File file = new File(filePath);     
InputStream is = new FileInputStream(file);

HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://mysomewebserver.com/services/doSomething.do");


byte[] data = IOUtils.toByteArray(is);

InputStreamBody isb = new InputStreamBody(new
ByteArrayInputStream(data), "filename");
StringBody sb1 = new StringBody("some text goes here");
StringBody sb2 = new StringBody("some text goes here too");
MultipartEntity multipartContent = new MultipartEntity();
multipartContent.addPart("uploadedFile", isb);
multipartContent.addPart("one", sb1);
multipartContent.addPart("two", sb2);

postRequest.setEntity(multipartContent);
HttpResponse response =httpClient.execute(postRequest);
response.getEntity().getContent().close();

但是有人警告说MultipartEntity会被贬低。我对此并不十分肯定。