我正在尝试从 Android 应用程序向使用 Tomcat 托管的 Java Servlet 发送 http 请求。该应用程序会将一些文本和图像数据发送到 servlet,但 servlet 似乎看不到多部分表单数据。我从本教程中获得了一些指导,以及一些 IRC 帮助确认传入数据:http ://blog.tacticalnuclearstrike.com/2010/01/using-multipartentity-in-android-applications/
安卓代码:
////库:httpclient-4.1.3、httpcore-4.1.4、httpmime-4.1.3、apache-mime4j-core-0.7.2
HttpPost httpPost = new HttpPost(mURI);
MultipartEntity requestEntity = new MultipartEntity();
requestEntity.addPart("text", new StringBody("test text"));
requestEntity.addPart("image", new ByteArrayBody(mImage, "image"));
httpPost.setEntity(requestEntity);
HttpResponse httpResponse = mHttpClient.execute(httpPost);
小服务程序代码:
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
File file = new File(getServletContext().getRealPath("/") + File.separator + "WEB-INF" + File.separator + "sms-mobile-image.jpg");
file.createNewFile();
Writer outfile = new OutputStreamWriter(new FileOutputStream(file));
List<Part> formData = new ArrayList(request.getParts());
if(formData.size()>0)
System.out.println(formData.get(0).getName());
else
System.out.println("no form data found");
} catch(Exception e) {
System.out.println(e.toString());
}
}
发送的实际数据(通过wireshark确认):
POST /mobile-image/ProcessRequest HTTP/1.1
Content-Length: 921897
Content-Type: multipart/form-data; boundary=ZiB5ibYqpxux_mP6HeswY9B__17vOLCVvay01
Host: 192.168.1.167:8080
Connection: Keep-Alive
--ZiB5ibYqpxux_mP6HeswY9B__17vOLCVvay01
Content-Disposition: form-data; name="text"
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 8bit
test text
--ZiB5ibYqpxux_mP6HeswY9B__17vOLCVvay01
Content-Disposition: form-data; name="image"; filename="image"
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
[image-data-here]
--ZiB5ibYqpxux_mP6HeswY9B__17vOLCVvay01--
输出:
no form data found
有人建议我查看 web.xml 配置,这将是我的下一步,但我在这里感到茫然。这不是它应该工作的方式吗?