我正在开发一款允许用户使用HttpPost方法上传图片的应用。我使用MultipartEntity,因此我将库apache-mime4j-0.6.1.jar,httpclient-4.3.1.jar,httpcore-4.3.1.jar和httpmime-4.2.1.jar添加到我的应用程序中。我的上传代码如下:
public String uploadFile() throws Exception
{
String result = "";
try
{
HttpResponse response = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(_url);
request.setHeader("Accept", "application/json");
File file=new File(filePath);
String fileName=file.getName();
MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));
imageEntity.addPart("imageName", new StringBody(fileName));
imageEntity.addPart("image", new FileBody(file, "application/octet-stream"));
request.setEntity(imageEntity);
response = httpClient.execute(request);
InputStream dataStream = response.getEntity().getContent();
BufferedReader dataReader = new BufferedReader(new InputStreamReader(dataStream));
String line = "";
while ((line = dataReader.readLine()) != null)
result+=line;
}
catch (Exception e)
{
}
return result;
}
我从我的服务器得到响应但在我的Web服务代码中Request.Files没有文件。如果我改变了行:
MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));
到
MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
应用程序正在进行很长时间(大约3-4分钟)并抛出错误。如果我添加图像会导致这种情况。如果我只发送没有FileBody的StringBody,我会在服务器和Request.Files中得到我的webservice代码返回文件计数的响应。如何解决此问题并正确上传图像?有什么建议吗?