gpt4 book ai didi

java - 将 JSON 数据发送到 servlet 结果为空字符串

转载 作者:太空宇宙 更新时间:2023-11-04 12:15:19 26 4
gpt4 key购买 nike

我已经搜索并测试了两天我找到的每个代码,但完全没有运气。我正在向 servlet 发送一个 json 文件,并且我非常确定数据已正确发送;由于某种原因,我无法从请求的输入流中获取它们。

这里是数据发送者的代码:

{
...
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());

Gson gson = new Gson();
String jsonString = gson.toJson(<POJO_to_send>).toString();
wr.writeBytes(URLEncoder.encode(jsonString,"UTF-8"));

wr.flush();
wr.close();

String responseMessage = con.getResponseMessage();
...
}

servlet 中的代码:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String s = "";
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));

while((s=br.readLine())!=null) {
s = br.readLine();
sb.append(s);
}

String jsonString = sb.toString();
if (jsonString != null) {
jsonString = br.readLine();
}else{
IOException ioex = new IOException("Error reading data.");
throw(ioex);
}
}

出于某种我尚未发现的原因,sb.toString() 结果为空值,因为 sb 是一个空字符串。从调试中我发现请求的输入流的 buf 值似乎不为空(至少其中有一些字节数据,并且在我看来它们与发送者的数据输出编写器相同)。

您是否看到了我错过的一些错误?我可以在数据到达 servlet 之前检查发送的数据吗(也许编码在某处失败)?

有什么建议/想法吗?

谢谢

最佳答案

DataOutputStream 是适得其反的。如果不传递内容类型和字符集,代码将变为:

对于 POST,人们会期望一个 HTML 表单参数,例如 json=...。不幸的是,发布表单数据需要更多格式化,所以让我们尝试一下。

HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setDoOutput(true);
con.connect(); // .............
OutputStream out = con.getOutputStream();

Gson gson = new Gson();
String jsonString = gson.toJson(<POJO_to_send>).toString() + "\r\n";
out.write(jsonString.getBytes(StandardCharsets.UTF_8));
out.close();

String responseMessage = con.getResponseMessage();

在每种情况下,对于请求方法 POST,都必须在 servlet 中使用 doPost

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

BufferedReader br = new BufferedReader(
new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));

StringBuilder sb = new StringBuilder();
String s;
while ((s = br.readLine()) != null) {
sb.append(s).append("\n");
}

String jsonString = sb.toString();
}

关于java - 将 JSON 数据发送到 servlet 结果为空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39472996/

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