I have the Javascript function below. Whenever I run it (calling it from an Android app using WebView), it is sent as an application/x-www-form-urlencoded
despite h
This works for me (I'm using Tomcat
, not Jetty
though). I didn't do anything with the JSON
payload, just tested if the URL on the server is hit.
AJAX (plain javascript)
function issueAjaxPost(){
var url = "http://localhost:8085/some_url/servlet/PostJson";
var json = '{ "action": "create", "userId": userId }';
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlhttp.send(json);
}
Servlet
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String url = request.getRequestURL().toString();
String page = url.substring(url.lastIndexOf("/"));
...
if("/PostJson".equals(page)){
response.setContentLength("success".length());
response.setContentType("text/plain");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().write("success");
}
}
AJAX callback (the result)
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txt2").innerHTML = this.responseText; //the result (success)
}
};