: Unrecognized token ‘Alarm‘: was expecting (JSON Stri

时间:2025-02-18 09:28:54

最近在使用httpclient进行post时远程接口发生报错

报错信息:

: JSON parse error: Unrecognized token 'Alarm': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false'); nested exception is : Unrecognized token 'Alarm': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')

原因及解决方法:

原因是请求参数格式不正确,不是标准的json格式,通过JSONObject对象把参数转为json字符串即可,即修改消息体构造代码。

报错代码:

public HttpEntity httpPost(String url, Alarm data){
        try{
            CloseableHttpClient httpClient = ();
            // 创建httpPost实例
            HttpPost post = new HttpPost(url);
            //构造消息头
            ("Content-type", "application/json; charset=utf-8");
            // 构造消息体
            StringEntity entity = new StringEntity((), ("application/json", "utf-8"));
            (entity);
            CloseableHttpResponse response = (post);
            HttpEntity responseEntity = ();
            int statusCode = ().getStatusCode();
            //最后关闭HttpClient资源.
            ();
            return responseEntity;
        }catch (Exception e){
            ();
            return null;
        }
    }

修改后的代码:

public HttpEntity httpPost(String url, Alarm data){
        try{
            CloseableHttpClient httpClient = ();
            // 创建httpPost实例
            HttpPost post = new HttpPost(url);
            //构造消息头
            ("Content-type", "application/json; charset=utf-8");
            // 构造消息体
            StringEntity entity = new StringEntity(new JSONObject(data).toString(), ("application/json", "utf-8"));
            (entity);
            CloseableHttpResponse response = (post);
            HttpEntity responseEntity = ();
            int statusCode = ().getStatusCode();
            //最后关闭HttpClient资源.
            ();
            return responseEntity;
        }catch (Exception e){
            ();
            return null;
        }
    }

JSONObject依赖:

        <dependency>
            <groupId></groupId>
            <artifactId>json</artifactId>
            <version>20211205</version>
        </dependency>