我正在发送一个 POST 请求,.send()
其中包含"id=jeff&command=test"
.
如何通过HttpServletRequest
对象在 Java 中解析和使用这些值?
我尝试将内容类型更改为text/html
and application/x-www-form-urlencoded
。我的Java服务器是嵌入式码头顺便说一句。
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);
这是我的 Java 代码
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);
这是我从浏览器发出请求时的输出
id=jeff&command=test (来自缓冲阅读器)
null (这是来自我的字符串 p 应该是 id)
这是 Chrome 的工具包的东西..
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)
我的服务器回复
{"flavor":"You are in the goHandler"}