我一直致力于通过多部分帖子将数据发送到 servlet。我的 Android 代码运行良好。但是在 servlet 中,当我尝试解析请求时,会收到我不理解的错误消息。
安卓
public void myClickHandler(View view)
{
//String path="http://10.0.2.2:8080/upload/uploadedimg";
String path="http://10.0.2.2:8080/ImageLocalizer/Localize";
String pathToFile="/sdcard/building.jpg";
text1.setText(path);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(path);
Bitmap bitmapOrg = BitmapFactory.decodeFile(pathToFile);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
//compressing the image byte array
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] data = bao.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data,"/sdcard/building.jpg");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("caption", new StringBody("nabeel"));
reqEntity.addPart("uploaded", bab);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
Toast.makeText(this, "Connection Established", Toast.LENGTH_LONG).show();
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String res,msg="";
while ( (res = in.readLine()) != null )
msg+=res;
text2.setText(msg);
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
伺服器
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
//List<FileItem> fileItems;
try {
System.out.println("There is somwething transfered");
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
System.out.println("DISK");
System.out.println("Iterator");
List<FileItem> fields = upload.parseRequest(request);
out.println("Number of fields: " + fields.size() + "<br/><br/>");
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
尝试使用时出现以下错误upload.parseRequest(request)
org.apache.tomcat.util.http.fileupload.FileUploadException: Stream closed
at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:336)
at org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:129)
at Localize.doPost(Localize.java:97)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)