我正在使用 Java、Spring boot 和 Apache HttpClient 尝试发送发布请求。我试图访问的资源的文档可以在这里找到:https://docs.enotasgw.com.br/v2/reference#incluiralterar-empresa下面是我的代码:CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost post = new HttpPost(incluirEmpresa);post.setHeader("Content-Type", "application/json");post.setHeader("Accept", "application/json");post.setHeader("Authorization", "Basic " + apiKey);try { StringEntity entity = new StringEntity(json); //tried to add these two lines to see if they would fix the error, but it is the same entity.setContentEncoding("application/json"); entity.setContentType("application/json"); post.setEntity(entity); System.out.println(json); System.out.println("======================"); CloseableHttpResponse response = httpClient.execute(post); System.out.println(response.getStatusLine().getReasonPhrase() + " - " + response.getStatusLine().getReasonPhrase()); idEmpresa = response.getEntity().getContent().toString();}我的回答是 400 - 错误的请求。在上面的交互式文档链接上,当我发布我的 Json 时,我收到重复条目的错误,这是我所期望的,因为我发送的信息已经在数据库中。由于交互式文档返回重复错误,我知道问题不在我的 json 格式内,而是在我的 post 请求中。文档有关于 C# 的示例,但没有关于 Java 的示例,这是我正在使用的。顺便说一句, json is variable 是一个字符串,以防万一。有人可以尝试指出我的邮政编码有什么问题吗?
1 回答
倚天杖
TA贡献1828条经验 获得超3个赞
发现我错过了什么。在查看发送到 API 的内容后,我注意到 json 不是预期的格式。所以我做了一些研究,发现至少在我的情况下,设置带有内容类型的标题是不够的,我还必须设置被设置为 HttpPost 的实体,要做到这一点,我必须改变这个代码行:
StringEntity entity = new StringEntity(json);
对此:
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
更改之后,请求开始按预期工作。
添加回答
举报
0/150
提交
取消