Problem#
At first glance, the following code looks seamless:
// Define format
final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("application/json; charset=UTF-8");
// Create object
final OkHttpClient client = new OkHttpClient();
// The answer here can be any string
String reqData = "{\n" +
" \"req_data\": {\n" +
" \"text\": \"" +
answer +
"\\n\",\n" +
" \"image_ids\": [],\n" +
" \"mentioned_user_ids\": []\n" +
" }\n" +
"}";
// Pass reqData as the request body
Request request = new Request.Builder()
.url("https://api.zsxq.com/v2/topics/" + t.getTopicId() + "/comments")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, reqData))
.addHeader("cookie", cookie)
.addHeader("Content-type", "application/json; charset=UTF-8")
.build();
But if there are line breaks in the answer:
answer = "Jiaxing University is a comprehensive university.\n\nJiaxing University offers undergraduate programs...";
Then the resulting reqData will have problems:
{
"req_data": {
"text": "Jiaxing University is a comprehensive university.
Jiaxing University offers undergraduate programs...\n",
"image_ids": [],
"mentioned_user_ids": []
}
}
Obviously, the format of this json is problematic
Solution#
We expect reqData to be like this:
{
"req_data": {
"text": "Jiaxing University is a comprehensive university.\n\nJiaxing University offers undergraduate programs...\n",
"image_ids": [],
"mentioned_user_ids": []
}
}
So we need to modify the answer:
answer = answer.replace("\n", "\\n");
String reqData = "{\n" +
" \"req_data\": {\n" +
" \"text\": \"" +
answer +
"\\n\",\n" +
" \"image_ids\": [],\n" +
" \"mentioned_user_ids\": []\n" +
" }\n" +
"}";