无法将文件附加到POST请求

时间:2014-04-17 11:44:44

标签: android file http-post multipartentity

我发送带有POST请求的文件时遇到问题。如果fileName有括号,则服务器根本不接收文件,否则服务器接收文件,其中插入了名称。

我已经尝试过使用   - 排球图书馆
  - appach httpmime不同版本
  - Android Asynchronous Http Client
我也有同样的结果。

这是我使用的代码

       String fileName = "link[image]";//name of the parameter         
       HttpContext localContext = new BasicHttpContext();
       MultipartEntityBuilder builder = MultipartEntityBuilder.create();
       builder.setLaxMode();
       builder.setCharset(Charset.forName("UTF-8"));
       builder.addBinaryBody(fileName, image, ContentType.APPLICATION_OCTET_STREAM, image.getName());//image - it's a File
       HttpClient client = new DefaultHttpClient();
       HttpPost post = new HttpPost(URL);
       HttpEntity entity = builder.build();
       post.setEntity(entity);
       HttpResponse response = client.execute(post, localContext);
       HttpEntity httpEntity = response.getEntity();
       String result = EntityUtils.toString(httpEntity);

1 个答案:

答案 0 :(得分:0)

试试这种方式

String fileName = "link[image]";
        HttpContext localContext = new BasicHttpContext();
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("image", new FileBody(new File(fileName)),"image/jpg");
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(URL);
        HttpEntity entity = builder.build();
        post.setEntity(entity);
        HttpResponse response = client.execute(post, localContext);
        HttpEntity httpEntity = response.getEntity();
        String result = EntityUtils.toString(httpEntity);