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

标签 java rest

我已经为 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/

相关文章:

java - 如果在 Java 中到达文件末尾,如何从控制台读取输入?

java - Redis - 存储和获取带有详细信息的有限 key

web-services - 在 REST 中处理添加/删除多对多关系的正确方法是什么?

javascript - location.path() AngularJS 方法中的重定向

api - 如何从 Magento REST API token 中获取用户 ID?

java - 查找 Java 中是否存在 Rest 服务中的方法

java - 使用 apache poi 读取 excel - Hashmap、ArrayList

java - Android onClick启动的两个动画,应该只启动一个

java - 如何使用数组创建密码和 ID 的 GUI java

REST 和 RDF,表示策略是什么?