繁体   English   中英

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

[英]Java code with POST request with newline in Json body issuing an error

我已经为REST服务器编写了Java客户端,除非将换行符添加到Json主体请求中的String,否则它可以完美地工作。 如果我使用诸如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

请记住,JSON字符串中不允许使用文字换行符。 它需要表示为\\n 但是,Java字符串中的换行符也表示为\\n 例如:

像这样的Java字符串

String example = "{\"test\":\"line\nbreak\"}"

将代表(JSON)字符串

{"test":"line
break"}

这是不允许的。 您需要JSON字符串为:

{"test":"line\nbreak"}

在Java字符串中表示为:

String example = "{\"test\":\"line\\nbreak\"}"
// Notice the double backslash ---^^

带有外部单词:就像您必须在Java字符串中使用反斜杠转义引号( " )一样,您还需要对其他反斜杠进行转义(例如\\n的一个)。

\\\\ n替换换行符\\ n并从最后的json项中删除逗号(,)

正确的语法如下

   String jsonBody = "{\"name\": \"Operation 101\",\"idPio\": \"10007200000000000205\",\"idGlobalPio\": \"5387fed1-d010-4bde-b45b-7dd5815b9e03\",\"text\": \"Descrition\\n1 - First line\\n2 - Second Line\"}";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM