Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Multipart POST to Google App Engine not working

I'm developing an android program that shares data via POST with an App Engine program, all in java. When I POST using MultipartEntity the appengine program is unable to see any of my POST variables for some reason that I can't figure out!

Appengine Code:

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/plain");
    resp.getWriter().println("Output:");

    String mRoutine = req.getParameter("Routine");
    resp.getWriter().println("Routine: " + mRoutine);

    String mPMode = req.getParameter("PMode");
    resp.getWriter().println("PMode: " + mPMode);
}

Working Android Snippet:

HttpPost post = new HttpPost("http://XXX.appspot.com/Echo");
HttpClient client = new DefaultHttpClient();
post.setEntity(new UrlEncodedFormEntity(data,HTTP.UTF_8));
HttpResponse response = client.execute(post);
HttpEntity resmarkMessagesReadFrom = response.getEntity();
if (resmarkMessagesReadFrom != null) {
    Result_STR= "Response:\n" + EntityUtils.toString(resmarkMessagesReadFrom);
    mMSGBox.setText(Result_STR);
}

Failing Android Snippet:

HttpPost post = new HttpPost("http://XXX.appspot.com/Echo");
HttpClient client = new DefaultHttpClient();
MultipartEntity reqmarkMessagesReadFrom = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
    reqmarkMessagesReadFrom.addPart("Routine", new StringBody("Neutral"));
    post.setEntity(reqmarkMessagesReadFrom);
    HttpResponse response = client.execute(post);
    HttpEntity resmarkMessagesReadFrom = response.getEntity();
    if (resmarkMessagesReadFrom != null) {
        Result_STR= "Response:\n" + EntityUtils.toString(resmarkMessagesReadFrom);
        mMSGBox.setText(Result_STR);
    }
like image 362
Robert Avatar asked Dec 17 '10 18:12

Robert


2 Answers

Using the MultipartEntity class on the client, you need to handle your doPost in a different way server side, reading the files/parameters with an API like the Apache Commons FileUpload.

Google App Engine does not allow to write to filesystem, so you need to use the Streaming API.

import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.io.InputStream;
..
public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      ServletFileUpload upload = new ServletFileUpload();
      res.setContentType("text/plain");

      FileItemIterator iterator = upload.getItemIterator(req);
      while (iterator.hasNext()) {
        String name = item.getFieldName();
        FileItemStream item = iterator.next();
        InputStream stream = item.openStream();

        if (item.isFormField()) {
          resp.getWriter().println((name + " : " + Streams.asString(stream));
        }
      }
    } catch (Exception ex) {
      throw new ServletException(ex);
    }
}
like image 189
systempuntoout Avatar answered Oct 04 '22 04:10

systempuntoout


Best answer I have found is one of google's own examples: http://code.google.com/intl/fr/appengine/kb/java.html#fileforms this uses FileUpload just like systempuntoout's example.

import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.io.InputStream;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FileUpload extends HttpServlet {
  private static final Logger log =
      Logger.getLogger(FileUpload.class.getName());

  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      ServletFileUpload upload = new ServletFileUpload();
      res.setContentType("text/plain");

      FileItemIterator iterator = upload.getItemIterator(req);
      while (iterator.hasNext()) {
        FileItemStream item = iterator.next();
        InputStream stream = item.openStream();

        if (item.isFormField()) {
          log.warning("Got a form field: " + item.getFieldName());
        } else {
          log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());

          // You now have the filename (item.getName() and the
          // contents (which you can read from stream).  Here we just
          // print them back out to the servlet output stream, but you
          // will probably want to do something more interesting (for
          // example, wrap them in a Blob and commit them to the
          // datastore).
          int len;
          byte[] buffer = new byte[8192];
          while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
            res.getOutputStream().write(buffer, 0, len);
          }
        }
      }
    } catch (Exception ex) {
      throw new ServletException(ex);
    }
  }
}
like image 27
Robert Avatar answered Oct 04 '22 05:10

Robert