我正在发送一个 POST 请求,.send()
部分有一个字符串,该字符串"id=jeff&command=test"
.
如何通过 HttpServletRequest
对象在 Java 中解析和使用这些值?
我尝试将内容类型更改为text/html
和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"}
"那行得通。但是,难道没有内置的方法来获得这些值吗?
不要读取输入流来获取参数,因为一旦读取输入流,您就会到达输入流的末尾,并且本机方法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);
您可以将其作为缓冲读取器获取。这将给出完整的字符串。您可以手动解析它。如果分隔符为"",则
,BufferedReader reader = request.getReader();
while ((str = reader.readLine()) != null)
jb.append(str);
编辑:
您可以尝试其中一个/两个这些 http 标头吗?!这是您更新的代码。
var text = form.command.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
var params = "id=jeff&command=" + encodeURIComponent(text);
xmlhttp.open("POST", "go", true);
xmlhttp.send(params);
使用 encodeURIComponent() 将 URI 转换为有效的 ASCII。
更新了JavsScript,因为默认内容类型是"application/x-www-form-urlencoded",因此将其删除。现在尝试访问 servlet 中的所有参数。