我正在发送一个 POST 请求,其中 .send()
部分是 "id=jeff&command=test"
。
如何通过 HttpServletRequest
对象在 Java 中解析和使用这些值?
我已尝试将内容类型更改为 text/html
和 application/x-www-form-urlencoded
。
顺便说一句,我的 Java 服务器是嵌入式 jetty 。
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(这是来 self 的字符串 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"}
最佳答案
“这行得通。但是没有内置的方法来获取这些值吗?”
不要读取输入流来获取参数,因为一旦您读取了输入流,您就到达了输入流的末尾,并且 native 方法 getParameter()
不会重置输入流,这就是它返回 null 的原因。
直接使用getParameter()
获取值。
使用 InputStream
或 getParameter()
不要同时使用两者
@Override
protected void doPost(HttpServletRequest request,HttpServletResponse response)throws IOException
{` `
String p=request.getParameter("id");
String input=request.getParameter("command");
System.out.println(p);
关于java - 如何使用 XMLHttpRequest.send(string) 中的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12787291/