Question

i'm trying to send an http request from an Android app to a Java Servlet hosted with Tomcat. the app would send some text and image data to the servlet, but the servlet does not seem to see the multipart form data. i've had a little direction from this tutorial as well as some IRC help with confirming the incoming data: http://blog.tacticalnuclearstrike.com/2010/01/using-multipartentity-in-android-applications/

Android code:
////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 code:

@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());
    }
}

Actual data sent (confirmed with 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--

output:

no form data found

it was suggested that i look through the web.xml config, so that'll be my next step, but i feel at a loss here. isn't this the way it's supposed to work?

Was it helpful?

Solution

i was able to solve this by using the com.oreilly.servlet package. it's a shame though, i still think i may be doing something wrong. this seems like something that should be built into the httpclient library... regardless, if you're interested, there are plenty of examples that make use of this library and the one i followed is here: http://www.jguru.com/faq/view.jsp?EID=1045507

posted in srinivas' reply somewhere down the page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top