2

simple problem (am confused I could not find an answer here):

I want to do a Multipart encoded HTTP POST from my AppEngine Java servlet (outbound). AppEngine does not seem to support the Apache HTTP lib and does not offer an API themselves (only setPayload(byte[])), but I would like to avoid implementing a Multipart encoding myself. So:

  1. Is there a way to send Multipart HTTP bodies from AppEngine Java?

  2. Is there a library that encodes such a body into a byte[] array? (Note that MultiPartEntity.getContent() is not implemented.) Then I could use the AppEngine internal URLFetch API (which I would prefer because of the async calling capabilities).

Daniel
  • 2,087
  • 3
  • 23
  • 37

2 Answers2

2

I wrote a little helper method that adds Multipart POST support to AppEngine (using the Apache HTTP client lib).

public static void addMultipartBodyToRequest(MultipartEntity entity, HTTPRequest req) throws IOException{

    /*
     * turn Entity to byte[] using ByteArrayOutputStream
     */
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    entity.writeTo(bos);
    byte[] body = bos.toByteArray();

    /*
     * extract multipart boundary (body starts with --boundary\r\n)
     */
    String boundary = new BufferedReader(new StringReader(new String(body))).readLine();
    boundary = boundary.substring(2, boundary.length());

    /*
     * add multipart header and body
     */
    req.addHeader(new HTTPHeader("Content-type", "multipart/form-data; boundary=" + boundary));
    req.setPayload(body);
}

The calling code then looks like this:

            MultipartEntity e = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            e.addPart("part1", new StringBody("value1"));
            e.addPart("part2", new StringBody("value2"));

            HTTPRequest req = new HTTPRequest(new URL(myUrl), HTTPMethod.POST);
            ServletHelper.addMultipartBodyToRequest(e, req);

            URLFetchServiceFactory.getURLFetchService().fetchAsync(req);
Daniel
  • 2,087
  • 3
  • 23
  • 37
0

You can use MultipartEntity from httpmime.

Hers is an example.

Community
  • 1
  • 1
Peter Knego
  • 79,991
  • 11
  • 123
  • 154
  • thanks. I ended up writing it myself (see above, comparable solution to your link, but using the low-level URLFetch Service instead). – Daniel Nov 27 '12 at 21:34