2013-05-15 115 views
4
private void CreateaMultiPartRequest() { 
    try{ 
     HttpClient client = new DefaultHttpClient(); 
     HttpPost post = new HttpPost("http://172.16.22.232:8080/RESTfulExample/rest/multiPartFileUpload"); 
     MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
     post.setHeader("Content-type", "multipart/form-data; boundary="+"~~~~~"); 
     String Usersettings = "{\"uId\":\"atcc02\", \"bomId\":\"IC014654_12345\", \"fileName\":\"file_12345.pdf\"}";  
     File cfile = new File(receivedUri.getPath()); 
     reqEntity.addPart("file", new FileBody(cfile,"application/octet")); 
     reqEntity.addPart("settings", new StringBody(Usersettings,"application/json",Charset.forName("UTF-8"))); 
     post.setEntity(reqEntity); 
     HttpResponse response = client.execute(post); 
     HttpEntity resEntity = response.getEntity(); 
      if (resEntity != null) 
       { 
        resEntity.consumeContent(); 
       } 
       else{      
       } 
      }   
      catch(Exception e) 
      { 
      } 
     } 

每當我嘗試執行此代碼時,iam從服務器獲取「400:BAD REQUEST」。在這裏無法解決問題,有人能幫我糾正這個問題嗎?Android中的多部分請求問題 - 投擲不良請求

+0

你檢查這http://stackoverflow.com/questions/11629013/android-error-multipartentity-request-sent-by-the-client-was-syntactically-i?rq=1 –

+0

是。 。我查了一下。其實我也跟着一樣。仍然有問題 –

+0

這是Android的代碼? MultipartEntity不是Android庫的一部分。 –

回答

0

在這裏,你可以試試這個,它爲我工作精細。

 HttpClient httpClient = new DefaultHttpClient(); 
     HttpContext localContext = new BasicHttpContext(); 
     HttpPost httpPost = new HttpPost(url); 

     FileBody bin = new FileBody(new File(args[5])); 
     long size = bin.getContentLength(); 

     MultipartEntity reqEntity = new MultipartEntity(); 
     reqEntity.addPart("image1", bin); 
     String content = ""; 
     try { 
      httpPost.setEntity(reqEntity); 
       HttpResponse response = httpClient.execute(httpPost, localContext); 
       HttpEntity ent = response.getEntity(); 
       InputStream st = ent.getContent(); 
       StringWriter writer = new StringWriter(); 
       IOUtils.copy(st, writer); 
       content = writer.toString();     

     } catch (IOException e) {     

     }