如何在HttpRequest的setBody中使用JSON?Apex接口调用报400错误
问题排查与解决方案
错误原因分析
你遇到的400错误是因为请求体的JSON格式无效,具体问题有三点:
- 错误的引号转义:代码中使用了
"(HTML转义的双引号),但在Apex字符串中直接使用双引号即可(用单引号包裹字符串时),"会被识别为普通字符,直接破坏JSON结构。 - 多余的尾逗号:
"value": "1646149510",末尾多了一个逗号,JSON语法不允许最后一个键值对后保留逗号。 - 手动拼接JSON易出错:手动拼接字符串很容易出现这类格式疏漏,属于不推荐的写法。
修复方案
方案1:修正手动拼接的JSON字符串
替换错误的引号转义字符,去掉多余的尾逗号:
public class makeCallOutIC1 { public String getContent(String url){ Http h = new Http(); HttpRequest req = new HttpRequest(); req.setEndpoint('https://api.intercom.io/contacts/search/'); req.setMethod('POST'); String authorizationHeader = 'Bearer ' + 'dGljA='; req.setHeader('Authorization', authorizationHeader); req.setHeader('Accept', 'application/json'); req.setHeader('Content-Type', 'application/json'); req.setHeader('Intercom-Version', '2.6'); // 修正后的JSON字符串:替换转义引号,移除尾逗号 String body = '{' + '"query": {' + ' "field": "last_seen_at", ' + ' "operator": ">", ' + ' "value": "1646149510" ' + ' }' + ' }'; req.setBody(body); HttpResponse res = h.send(req); return res.getBody(); } }
方案2:用Apex类序列化生成JSON(推荐)
创建对应JSON结构的Apex内部类,通过JSON.serialize()自动生成格式正确的JSON,彻底避免手动拼接的错误:
public class makeCallOutIC1 { // 内部类映射请求体的JSON结构 public class ContactSearchRequest { public Query query; public class Query { public String field; public String operator; public String value; } } public String getContent(String url){ Http h = new Http(); HttpRequest req = new HttpRequest(); req.setEndpoint('https://api.intercom.io/contacts/search/'); req.setMethod('POST'); String authorizationHeader = 'Bearer ' + 'dGljA='; req.setHeader('Authorization', authorizationHeader); req.setHeader('Accept', 'application/json'); req.setHeader('Content-Type', 'application/json'); req.setHeader('Intercom-Version', '2.6'); // 构建请求参数对象 ContactSearchRequest requestObj = new ContactSearchRequest(); requestObj.query = new ContactSearchRequest.Query(); requestObj.query.field = 'last_seen_at'; requestObj.query.operator = '>'; requestObj.query.value = '1646149510'; // 序列化为标准JSON字符串 String body = JSON.serialize(requestObj); req.setBody(body); HttpResponse res = h.send(req); return res.getBody(); } }
额外说明
- 序列化方式不仅能避免格式错误,还能让代码更易读、易维护,后续修改参数只需调整类的属性即可。
- 可以通过
System.debug(body);输出序列化后的字符串,提前验证JSON格式是否符合Intercom API的要求。
内容的提问来源于stack exchange,提问作者Ruby Khan
相关产品推荐
相关产品推荐

