gpt4 book ai didi

带有换行符的 POST 请求的 Java 代码在 Json 正文中发出错误

转载 作者:行者123 更新时间:2023-11-29 07:24:49 25 4
gpt4 key购买 nike

我已经为 REST 服务器编写了一个 Java 客户端,除非在 Json 正文请求中的字符串中添加换行符,否则它可以完美运行。如果我使用诸如 Insomnia 之类的客户端,则相同的请求可以完美地处理换行符。 Javascript/HTML 客户端也可以很好地处理相同的数据。在下面的 Json 示例中,问题出在字段“文本”上。如果我删除“\n”代码有效。否则服务器返回错误 400。

我在请求中尝试了几种不同的编码和参数。似乎没有任何效果。

Json request formated
{
"name": "Operation 101",
"idPio": "10007200000000000205",
"idGlobalPio": "5387fed1-d010-4bde-b45b-7dd5815b9e03",
"text": "Description\n1 - First line\n2 - Second Line",
}

我的java代码

//If I just remove the "\n" from the String below the server issues the 200 code
//But the server will accept this string just as it is if sent form Insomnia, handling correctly the newlines.
String jsonBody = "{\"name\": \"Operation 101\",\"idPio\": \"10007200000000000205\",\"idGlobalPio\": \"5387fed1-d010-4bde-b45b-7dd5815b9e03\",\"text\": \"Descrition\n1 - First line\n2 - Second Line\",}";

url = new URL("https://10.120.43.23:8000/api/item/1.0/item/annotation/?t=E34B2A8A-0A64-469A-AE52-45E8A9885D70");

HttpsURLConnection con = (HttpsURLConnection)url.openConnection();

//Add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Java client");
con.setRequestProperty("Accept-Language", "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7,fr;q=0.6");
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Accept", "application/json, text/plain, */*");
con.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
con.setRequestProperty("Connection", "keep-alive");
con.setDoOutput(true);

//Prepare data and send
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
byte[] arr = jsonBody.getBytes("UTF-8");
wr.write(arr);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println(String.valueOf(responseCode));

最佳答案

将换行符替换为 \\\n 而不是 \n

关于带有换行符的 POST 请求的 Java 代码在 Json 正文中发出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55494714/

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