【问题标题】:Receiving an Ajax Request in a Servlet using ObjectInputStream?使用 ObjectInputStream 在 Servlet 中接收 Ajax 请求?
【发布时间】:2012-05-25 06:57:16
【问题描述】:

我正在按以下格式发送我的 Ajax 请求

xmlhttp.open("POST","http://172.16.xx.xx:8080/ajax/validate",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(send); //where send is a string retrieved from textarea

这是我的 Servlet 代码

ObjectInputStream in =new ObjectInputStream(request.getInputStream()); 
String inputxmlstring=(String) in.readObject();

我收到以下异常

java.io.StreamCorruptedException: invalid stream header: 3C3F786D

代码有什么问题?我的请求标头内容类型有什么问题吗?

EDIT 1

             BufferedInputStream in =new BufferedInputStream(req.getInputStream());
             byte[] buf=new byte[req.getContentLength()];
             while(in.available()>0)
             {
              in.read(buf);
             }
             String inputxmlstring=new String(buf);
             System.out.println(inputxmlstring);

如果我将此代码用于 Servlet,我会收到以下错误

14:13:27,828 INFO  [STDOUT] [Fatal Error] :1:1: Content is not allowed in prolog
.
14:13:27,843 INFO  [STDOUT] org.xml.sax.SAXParseException: Content is not allowe
d in prolog.


编辑 2
我使用此代码进行解析。字符串 inputxmlstring 已在 Edit1 中使用。

DocumentBuilderFactory fty1 = DocumentBuilderFactory.newInstance();
fty1.setNamespaceAware(true);
DocumentBuilder builder1 = fty1.newDocumentBuilder();
ByteArrayInputStream bais1 = new ByteArrayInputStream(inputxmlstring.getBytes());
Document xmldoc1=builder1.parse(bais1);

【问题讨论】:

标签: ajax servlets inputstream


【解决方案1】:

您应该仅在知道另一端是使用 ObjectOutputStream 编写的情况下才使用 ObjectInputStream。

当客户端使用ObjectOutputStream 时,它会写入特殊的字节表示它是对象流。如果这些字节不存在,ObjectInputStream 将抛出 StreamCorruptedException。

在您的情况下,您应该使用 request.getInputStream() 阅读,因为 XMLHttpRequest 没有使用 ObjectOutputStream 发送。

【讨论】:

  • 如何使用 request.getinpustream() 直接读取。我想你必须把它包裹在一个缓冲的输入流或类似的东西上。
  • @suraj 你能发布堆栈跟踪吗
  • @suraj in EDIT1 我没有看到您解析 XML,这将抛出 org.xml.sax.SAXParseException: Content is not allowed in prolog。缺少一些东西,
  • 你得到什么响应字符串?你能打印出来吗?我认为它不是 XML 格式的。
  • @RameshPVK Servlet 或 AJAX 中的响应字符串?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-07
  • 2011-12-26
  • 2011-03-01
  • 1970-01-01
  • 2012-02-26
  • 2012-04-11
  • 1970-01-01
相关资源
最近更新 更多