Curl调用Spring Boot接口返回乱码,未获取预期内容求助
Hey there, let's break down why you're getting unreadable garbled characters instead of the plain text response you expect, and fix this issue step by step.
Common Causes & Solutions
1. Missing Character Encoding in Backend Response
Your current ResponseEntity doesn't specify a character encoding, and Spring defaults to ISO-8859-1 for text responses in some scenarios. If your client (curl) expects UTF-8—the standard for modern APIs—this mismatch can cause garbled text, even for simple strings like "Message Received".
Update your backend code to explicitly set UTF-8 encoding for both success and error responses:
@Override public ResponseEntity<String> add(@RequestBody Message message) { try { message.setTime(new Timestamp(new Date().getTime())); repository.save(message); // Set UTF-8 encoding for success response return ResponseEntity.ok() .contentType(new MediaType(MediaType.TEXT_PLAIN, StandardCharsets.UTF_8)) .body("Message Received"); } catch (Exception e) { // Apply the same encoding to error responses to avoid garbled exception details return ResponseEntity.status(HttpStatus.CONFLICT) .contentType(new MediaType(MediaType.TEXT_PLAIN, StandardCharsets.UTF_8)) .body(e.toString()); } }
Note: If you prefer returning JSON-formatted messages instead of plain text, switch the media type to MediaType.APPLICATION_JSON with UTF-8, and wrap the message in quotes to make it valid JSON (e.g., "Message Received").
2. Explicitly Specify Encoding in cURL Request
While curl usually handles UTF-8 by default, adding explicit headers removes any ambiguity between client and server expectations:
curl -H "Content-Type: application/json; charset=UTF-8" \ -H "Accept-Charset: UTF-8" \ -X POST \ -d "{\"time\": \"2019-12-27T09:50:02.000+0000\", \"unread\": true, \"message\": \"asd\", \"from\": \"Vadim\"}" \ localhost:8080/api/save
Why This Works
By aligning both the server's response encoding and the client's expected encoding to UTF-8, you eliminate the character set mismatch that's causing the garbled output. This fixes issues for both your success message and any exception details that might be returned.
Give these changes a shot—your response should show up as the clear "Message Received" you expect!
内容的提问来源于stack exchange,提问作者damagedd

