Unirest无法正确生成JSON字符串,调用REST API报错求助
解决Unirest POST请求JSON格式异常问题
你碰到的这个问题其实是个常见误区——你用.field()方法的时候,Unirest默认会按照**表单格式(application/x-www-form-urlencoded)**发送请求,完全不是你想要的JSON格式!这就导致后端接收数据时解析出错,返回的错误信息又被Unirest尝试转成JsonNode,最终抛出了那个JSONArray格式错误的异常。
要让Unirest自动处理JSON请求,得换正确的姿势写代码,下面给你几个可行的方案:
方案1:用JSONObject构建请求体(最直观)
try { // 先把参数组装成JSON对象 JSONObject requestBody = new JSONObject(); requestBody.put("text", "Good job"); requestBody.put("timestamp", "123455677777"); requestBody.put("senderId", "5"); requestBody.put("receiverId", "2"); HttpResponse<JsonNode> jsonResponse = Unirest.post(URL + "employees/comments") .header("accept", "application/json") .header("Content-Type", "application/json") // 明确告诉服务器我们发的是JSON .body(requestBody) .asJson(); } catch (UnirestException e) { e.printStackTrace(); }
方案2:用Map构建请求体(更易维护)
如果不想直接操作JSONObject,用Map也能让Unirest自动转成JSON:
try { Map<String, Object> requestParams = new HashMap<>(); requestParams.put("text", "Good job"); requestParams.put("timestamp", "123455677777"); requestParams.put("senderId", "5"); requestParams.put("receiverId", "2"); HttpResponse<JsonNode> jsonResponse = Unirest.post(URL + "employees/comments") .header("accept", "application/json") .header("Content-Type", "application/json") .body(requestParams) .asJson(); } catch (UnirestException e) { e.printStackTrace(); }
方案3:直接传入JSON字符串(适合简单场景)
如果参数不多,直接写JSON字符串也可以,用.jsonBody()方法更简洁:
try { HttpResponse<JsonNode> jsonResponse = Unirest.post(URL + "employees/comments") .header("accept", "application/json") .jsonBody("{\"text\":\"Good job\",\"timestamp\":\"123455677777\",\"senderId\":\"5\",\"receiverId\":\"2\"}") .asJson(); } catch (UnirestException e) { e.printStackTrace(); }
核心要点就是:别用.field()来发JSON请求,那是给表单提交用的。只要你用.body()传入JSON对象/Map,或者用.jsonBody()传入JSON字符串,再加上Content-Type: application/json的请求头,Unirest就会自动帮你处理JSON的序列化和解析了。
内容的提问来源于stack exchange,提问作者snubben
相关产品推荐
相关产品推荐

