SpringBoot调用Rasa API返回400 Bad Request问题排查
SpringBoot调用Rasa API返回Bad Request的解决方案
你的代码核心问题是请求头与请求体格式不匹配:
- 你设置了
Content-Type: application/json,但实际发送的是表单编码的请求体(UrlEncodedFormEntity),Rasa的REST webhook无法解析这种格式,因此返回Bad Request。 - Rasa的
/webhooks/rest/webhook接口要求接收JSON格式的请求体,结构为{"message": "你的消息内容"}。
修正步骤:
- 将请求体改为JSON字符串,使用
StringEntity承载(如果项目引入Jackson,也可以用ObjectMapper序列化对象)。 - 确保
Content-Type头与请求体格式完全一致。 - 正确读取Rasa返回的响应内容,而非仅消费实体。
修正后的代码
如果需要用Jackson处理JSON,可先添加依赖(若项目未引入):
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> </dependency>
修改后的接口代码:
import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.io.entity.StringEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController public class ChatController { @PostMapping("/chat-2") public String chat(@RequestParam String message) { String rasaEndpoint = "http://localhost:5005/webhooks/rest/webhook"; CloseableHttpClient httpclient = HttpClients.createDefault(); ObjectMapper objectMapper = new ObjectMapper(); try { // 构建JSON格式的请求体 Map<String, String> requestBody = new HashMap<>(); requestBody.put("message", message); String jsonBody = objectMapper.writeValueAsString(requestBody); HttpPost httpPost = new HttpPost(rasaEndpoint); httpPost.setHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType()); httpPost.setEntity(new StringEntity(jsonBody, ContentType.APPLICATION_JSON)); return httpclient.execute(httpPost, response -> { System.out.println(response.getCode() + " " + response.getReasonPhrase()); if (response.getCode() == 200) { // 读取并返回Rasa的响应内容 String responseBody = EntityUtils.toString(response.getEntity()); return responseBody; } else { return "请求失败:" + response.getReasonPhrase(); } }); } catch (Exception e) { System.out.println("Error : " + e); return "请求异常:" + e.getMessage(); } finally { try { httpclient.close(); } catch (Exception e) { e.printStackTrace(); } } } }
额外说明
- 原代码硬编码了消息内容
"hi",修正后改为使用传入的message参数,更符合接口设计逻辑。 - 新增HttpClient的关闭逻辑,避免资源泄漏。
- 增加了响应状态判断与内容读取,方便直接获取Rasa的回复结果。
内容的提问来源于stack exchange,提问作者Meg
相关产品推荐
相关产品推荐

