0

I am trying to send a post request to mongohq server from my AppEngine using rest api.

I use this code:

public static void post(String id, String context)
{
  String urlString = "https://api.mongohq.com/databases/db/collections/collection/documents?_apikey=XXXXXXXXXX";
  String data = "{\"document\" : {\"_id\": \"" + id+ "\", \"context\":" + context +"}}";
  try
  {
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("charset", "utf-8");
    connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
    connection.setUseCaches(false);

    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes(data);
    wr.flush();
    wr.close();
    System.out.println(connection.getResponseMessage());
    connection.disconnect();
  }
  catch (Exception e)
  {
      System.out.println("postToMongo: "+ e);     
  }
}

It works perfectly from outside Appengine, but when I do the same from inside Appengine nothing is sent to mongodb.

The function prints OK in both outside and inside Appengine, but the data appears in the db only when I use this function outside Appengine.

Also, a simple jave get function works both outside and inside Appengine.

Can anyone help me with this problem? I search for a way to post to Mongohq from inside Appengine.

Thanks

Ygandelsman
  • 453
  • 7
  • 16
  • Try not setting the `Content-Length` header, as it's set automatically by GAE: https://developers.google.com/appengine/docs/java/urlfetch/#Java_Request_headers – Peter Knego Sep 20 '13 at 21:55
  • Also try using `OutputStreamWriter` instead of `DataOutputStream ` as shown in example: https://developers.google.com/appengine/docs/java/urlfetch/usingjavanet#Using_HttpURLConnection – Peter Knego Sep 20 '13 at 22:01
  • @PeterKnego, I changed. I still have the same problem... – Ygandelsman Sep 20 '13 at 22:05
  • So it seems that the POST is actually reaching destination (since you get the response), but data is not parsed properly on the other side. Two things to note: as already mentioned don't use `DataOutputStream` as this is for writing Java type to output stream. Second, default encoding on GAE is US-ASCII, so you must explicitly convert to UTF-8. – Peter Knego Sep 21 '13 at 07:03

1 Answers1

0

Try this:

 OutputStreamWriter writer;
 writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
 writer.write(message);
 writer.close();
Peter Knego
  • 79,991
  • 11
  • 123
  • 154