You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Curl调用Spring Boot接口返回乱码,未获取预期内容求助

Fixing Garbled Response Instead of Expected "Message Received"

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:02:29