Java向FastApi发送POST请求JSON负载遇422错误,求排查解决
问题:Java向FastAPI发送POST请求无法解析数据
尝试从Java端向FastAPI发送POST请求,多次尝试网上方案均失败,FastAPI无法正确接收或解析数据。
Java请求代码
public JSONObject saveData(JSONObject data) { JSONObject jsonResponse; try { HttpClient client = newHttpClient(); HttpRequest request = HttpRequest.newBuilder(URI.create(apiUrl + "save_variants")) .version(HttpClient.Version.HTTP_2) .header("accept", "application/json") .POST(HttpRequest.BodyPublishers.ofString(data.toString())) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); String jsonString = response.body().replaceAll("\\",""); jsonResponse = new JSONObject(jsonString); } catch (Exception e) { throw new RuntimeException(e); } System.out.println("Received updated data:" + jsonResponse); return jsonResponse; }
FastAPI接口代码
class Item(BaseModel): item: str @app.post("/variants") async def save_variants(item: Item): logger.info(f"Payload:${item}") return read_param_json("variant_parameters_original.json")
收到的错误响应
Received updated data:{"detail":[{"msg":"Field required","loc":["body"],"input":null,"type":"missing"}]}
问题根源与修复方案
问题1:请求路径不匹配
Java代码中请求的路径是save_variants,但FastAPI的接口路径是/variants,两者不一致,导致FastAPI无法匹配到对应的接口,自然无法解析请求体。
问题2:缺少Content-Type请求头
发送JSON格式的请求体时,必须通过Content-Type: application/json告诉服务器请求体的格式,否则FastAPI会默认无法识别请求体,返回body缺失的错误。
问题3:错误的JSON字符串处理
Java代码中的replaceAll("\\","")写法语法错误(正确转义应为replaceAll("\\\\", "")),且完全没必要执行该操作——它会破坏返回的JSON结构,导致解析异常。
修正后的Java代码
public JSONObject saveData(JSONObject data) { JSONObject jsonResponse; try { HttpClient client = HttpClient.newHttpClient(); // 修正请求路径,与FastAPI接口一致 HttpRequest request = HttpRequest.newBuilder(URI.create(apiUrl + "/variants")) .version(HttpClient.Version.HTTP_2) .header("accept", "application/json") // 添加Content-Type头,指定请求体为JSON格式 .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(data.toString())) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); // 直接解析响应JSON,移除错误的replaceAll操作 jsonResponse = new JSONObject(response.body()); } catch (Exception e) { throw new RuntimeException(e); } System.out.println("Received updated data:" + jsonResponse); return jsonResponse; }
额外注意事项
确保传入的dataJSONObject包含item字段,例如构造的JSON应为{"item": "你的内容"},与FastAPI中Item模型的字段对应。
内容的提问来源于stack exchange,提问作者Kris Rice
相关产品推荐
相关产品推荐

