I’m sending a POST request with a string in the .send() part which is "id=jeff&command=test".
How do I parse and use these values in Java via the HttpServletRequest object?
I’ve tried changing the content type to text/html and application/x-www-form-urlencoded.
My java server is embedded jetty btw.
var text = form.command.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
xmlhttp.responseText
}
}
xmlhttp.open("POST", 'go', true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("id=jeff&command=" + text);
here’s my Java code
public class GoHandler extends HttpServlet
{
Commands c = Commands.getInstance();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
BufferedReader reader = request.getReader();
String str = "";
while ((str = reader.readLine()) != null)
{
System.out.println(str);
}
String p = request.getParameter("id");
String input = request.getParameter("command");
System.out.print(p);
here is my output when I make the request from a browser
id=jeff&command=test (this is from the buffered reader)
null (this is from my String p which should be the id)
here’s Chrome’s toolkit thing..
Request URL:http://localhost:8080/go
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:20
Content-Type:application/xml
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4
Request Payload
id=jeff&command=test
Response Headersview source
Content-Length:66
Content-Type:application/json;charset=utf-8
Server:Jetty(8.1.7.v20120910)
my response from the server
{"flavor":"You are in the goHandler"}
You can get it as buffered reader. This will give full string. The you can parse it manually. If your separator is “\n” then,
Edit:
Can you try one/both of these http headers?! Here is your updated code.
Using encodeURIComponent() to convert the URI into valid ASCII.
Updated the JavsScript since the default content-type is “application/x-www-form-urlencoded” so removed it. Now try to access all your parameters in the servlet.