Answer the question
In order to leave comments, you need to log in
How to solve encoding problem when POST JSON to servlet?
Hello.
in java script ajax request send JSON using POST method
var json=[{"FUNCTION_GROUP":"Футбол"},{"FUNCTION_GROUP":"Шахматы"},{"FUNCTION_GROUP":"Плавание"}];
$.ajax({
type: 'POST',
url: 'employees',
data: JSON.stringify(json),
success: function(data) {
console.log( "Данные зафиксированы успешно.");
},
error: function(data) {
console.log( "Отправка данных завершилась завершилась ошибкой: ");
},
contentType: "application/json",
dataType: 'json'
});
Request URL:http://localhost:8000/employees
Request Method:POST
Status Code:200
Remote Address:[::1]:8000
Response Headers
view source
Content-Length:97
Date:Wed, 14 Jun 2017 18:19:20 GMT
Request Headers
view source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:97
Content-Type:application/json
Host:localhost:8000
Origin:http://localhost:8000
Referer:http://localhost:8000/LoginUser
User-Agent:Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
view source
[{FUNCTION_GROUP: "Футбол"}, {FUNCTION_GROUP: "Шахматы"}, {FUNCTION_GROUP: "Плавание"}]
0
:
{FUNCTION_GROUP: "Футбол"}
1
:
{FUNCTION_GROUP: "Шахматы"}
2
:
{FUNCTION_GROUP: "Плавание"}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
StringBuilder sb = new StringBuilder();
BufferedReader br = request.getReader();
String str;
while( (str = br.readLine()) != null ){
sb.append(str);
}
try {
JSONObject jObj = new JSONObject(sb.toString());
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(sb.toString());
response.getWriter().append(sb.toString());
}
[{"FUNCTION_GROUP":"Ðарды"},{"FUNCTION_GROUP":"Шахматы"},{"FUNCTION_GROUP":"ОБЖ"}]
Answer the question
In order to leave comments, you need to log in
Try specifying response.setContentType("application/json; charset=utf-8");
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question