我尝试将来自Android应用的http请求发送到使用Tomcat托管的Java Servlet。应用程序会将一些文本和图像数据发送到servlet,但servlet似乎没有看到多部分表单数据。我已经从本教程中获得了一些指导以及一些确认传入数据的IRC帮助:http://blog.tacticalnuclearstrike.com/2010/01/using-multipartentity-in-android-applications/
Android代码:
//// libs: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);
servlet代码:
@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配置,以便我的下一步,但我觉得这里不知所措。这不是它应该工作的方式吗?
答案 0 :(得分:0)
我能够使用com.oreilly.servlet
包来解决这个问题。虽然这很遗憾,我仍然认为我可能做错了什么。这似乎应该被构建到httpclient库中......无论如何,如果你感兴趣,有很多例子可以使用这个库,我所遵循的就是:
http://www.jguru.com/faq/view.jsp?EID=1045507
在页面的某处发布了srinivas的回复。