2013-10-08 35 views
1

以下代码给出错误的请求错误,代码中的任何解决方案或错误。上传文件Android org.apache.http.entity.mime.MultipartEntity:错误的请求错误

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 

预先感谢您

+0

和哪里是Web服务代码? –

+1

正确详细说明您的问题 – 2013-10-08 15:48:55

+0

错误的请求:400是客户端请求错误 在它进入webservice之前发生异常。 该web服务代码已经使用正常的html multipart/form-data进行了测试 如果在webservice上有任何错误,它会给出500+错误 – sawbeanraz

回答

0

正如萨蒂亚Komatineni,戴夫·麦克莱恩,赛义德Y.在书临的Android 3.0提到哈希米。 外部库中加入:

共享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被取消了。我对此不太确定。