Friday, July 2, 2010

App Engine and long Post URLs Error 414

I've been working on an applciation utilizing Google's App Engine. The fist version of my application sent about 500 bytes of information along with each user POST request. The second version up this to around 100 bytes and the App Engine server started giving the error:


Requested URI too long: ... HTTP/1.1" 414 –


This is the http error returned when a post request is longer than the server is configured to accept. After a little research I found this excellent article:

http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

that solved my problem. The short version of the article is:

Don’t send the post parameters as part of the url, send them using the XMLHTTP object’s send method once the object has been opened using only the address, (everything before the ?), of the original post url.

So, the original code that looked like:


var my_url = "/myhandler?longstring=" +

encodeURIComponent(longstring) +

//Now send the string to the db

if (typeof XMLHttpRequest != "undefined") {

req = new XMLHttpRequest();

} else if (window.ActiveXObject) {

req = new ActiveXObject("Microsoft.XMLHTTP");

}

req.open("POST", my_url, true);

req.onreadystatechange = my_cb;

req.send(null);


Becomes code that looks like:


var my_url = "longstring=" +

encodeURIComponent(longstring) +

//Now send the string to the db

if (typeof XMLHttpRequest != "undefined") {

req = new XMLHttpRequest();

} else if (window.ActiveXObject) {

req = new ActiveXObject("Microsoft.XMLHTTP");

}

req.open("POST", '/myhandler', true);

req.setRequestHeader("Content-type",

"application/x-www-form-urlencoded");

req.setRequestHeader("Content-length", score_params.length);

req.setRequestHeader("Connection", "close");

req.onreadystatechange = log_scores_cb;

req.send(score_params);

Notice that the call to send was changed from a null argument to the POST command arguments sent in the original URL. Also notice that the length of the parameters was sent to the server ahead of time in the 'Content-length' header.

No comments: