gpt4 book ai didi

java - servlet接收xml数据时出错

转载 作者:行者123 更新时间:2023-11-29 03:32:51 24 4
gpt4 key购买 nike

服务器代码

System.out.println(" ================servlet==================");
InputStream in = request.getInputStream();
int a = in.available();
byte[] b = new byte[a];
in.read(b);
String stringValue = new String(b,"utf-8");
System.out.println("receive data==="+stringValue);
OutputStream dataOut = response.getOutputStream();
String responseData = "<test>test</test>";
System.out.println("response datea==="+responseData);
dataOut.write(responseData.getBytes("utf-8"));
dataOut.flush();
dataOut.close();

客户端代码

System.out.println("================client======================");
java.net.URL url = new java.net.URL("test address");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
String sendData = "<data>send</data>";
System.out.println("send data="+sendData);
OutputStream dataOut = con.getOutputStream();
dataOut.write(sendData.getBytes("utf-8"));
dataOut.flush();
dataOut.close();
InputStream in = con.getInputStream();
int a = in.available();
byte[] b = new byte[a];
in.read(b);
String stringValue = new String(b,"utf-8");
in.close();
System.out.println("receive data="+stringValue);

我得到了打印结果servlet控制台 ================servlet================== 接收数据=== 响应日期a===test

客户端控制台

================client======================
send data=<data>send</data>
receive data=<test>test</test>

我的问题是servlet收不到客户端的数据

谁能帮帮我?

最佳答案

My question is that servlet can't receive the data from the client

这可能不是唯一的问题,但这段代码完全被破坏了:

int a = in.available();
byte[] b = new byte[a];
in.read(b);

您假设所有数据在一开始就可用。您应该改为从流中读取数据,直到数据用完为止。鉴于您希望将结果作为文本,我会将流包装在 InputStreamReader 中并从那里读取。例如:

BufferdReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Servlet read line: " + line);
}

如果您实际上想要将其作为 XML 读取,您应该能够将 InputStream(或 Reader)传递给 XML 解析器用于创建 DOM 的库。

顺便说一句,您也应该在客户端代码中做同样的事情。基本上:

  • 永远不要忽略InputStream.read的返回值
  • 避免使用available();这很少是合适的
  • 使用 InputStreamReader 从流中读取文本,而不是自己从字节构造文本
  • 使用 XML API 读取 XML 而不是将其作为原始文本处理

关于java - servlet接收xml数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17206572/

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