gpt4 book ai didi

java - 从 doPost HttpServletRequest 读取 xml 时出错

转载 作者:太空宇宙 更新时间:2023-11-04 07:50:20 27 4
gpt4 key购买 nike

我正在尝试读取使用 http doPost 方法发布的 XML 文件。使用 SAXParser 解析时会抛出异常:

Content is not allowed in prolog.

doPost 代码是:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
{
ServletInputStream httpIn = request.getInputStream();
byte[] httpInData = new byte[request.getContentLength()];
StringBuffer readBuffer = new StringBuffer();
int retVal = -1;
while ((retVal = httpIn.read(httpInData)) != -1)
{
for (int i=0; i<retVal; i++)
{
readBuffer.append(Character.toString((char)httpInData[i]));
}
}

System.out.println("XML Received" + readBuffer);
try
{
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
ByteArrayInputStream inputStream = new ByteArrayInputStream(
readBuffer.toString().getBytes("UTF-8"));
final XmlParser xmlParser = new XmlParser();
parser.parse(inputStream, xmlParser);
}
catch (Exception e)
{
System.out.println("Exception parsing the xml request" + e);
}
}

这是我正在测试的 JUnit:

public static void main(String args[])
{
StringBuffer buffer = new StringBuffer();
buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
buffer.append("<person>");
buffer.append("<name>abc</name>");
buffer.append("<age>25</age>");
buffer.append("</person>");

try
{
urlParameters = URLEncoder.encode(buffer.toString(), "UTF-8");
}
catch (Exception e1)
{
e1.printStackTrace();
}

String targetURL = "http://localhost:8888/TestService";

URL url;
HttpURLConnection connection = null;
try
{
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/xml");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes("UTF-8").length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);

//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
}
catch (Exception e)
{
e.printStackTrace();
}

我得到的 servlet 中的 XML 输出是这样的:

XML Received %3C%3Fxml+version%3D%221.0%22+encoding%3D%22UTF-8%22%3F%3E%3Cperson%3E%

所以这会在 SAXparser 中引发异常:

我做错了什么?我是否以错误的方式发送 XML 或以错误的方式读取 XML?

最佳答案

你假设

httpInData[i]

是一个字符,而它是一个字节。您的内容是 UTF-8,这会产生很大的差异。请改用阅读器。

然后,您对 XML 进行 URLEncoding,这是无用的,因为它是 POST 数据。不要对其进行编码,只需发送数据即可。

替换

urlParameters = URLEncoder.encode(buffer.toString(), "UTF-8");

urlParameters = buffer.toString();

此外,名称 urlParameter 选择不当,因为这是一个单独的帖子正文,不会出现在 url 中,也不是真正的参数。

关于java - 从 doPost HttpServletRequest 读取 xml 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14588471/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com