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)
            {
            }
        }

每当我尝试执行此代码时,我都会从服务器收到“400:BAD REQUEST”。无法在这里找出问题,有人可以帮助我纠正这个问题吗?

4

2 回答 2

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) {                   

        }
于 2013-06-17T15:49:04.457 回答
0

可能您对 FileBody 使用了错误的 MIME 类型。改用 application/octet-stream。

为了获得正确的 MIME 类型,我使用以下代码:

MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);

看看我用来发出网络请求的小库:http ://code.google.com/p/android-dman/source/browse/trunk/src/org/nkuznetsov/lib/dman/DownloadManager.java

于 2013-06-17T10:10:02.587 回答