Post 与 HttpClient returns 错误请求
Post with HttpClient returns Bad Request
我正在使用 Java、Spring 引导和 Apache HttpClient 尝试发送 post 请求。可以在此处找到我尝试访问的资源的文档:
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 - 错误请求。在上面的交互式文档 link 中,当我 post 我的 Json 时,我收到了重复输入的错误,这是我所期望的,因为我发送的信息已经在数据库中。
由于交互式文档returns重复错误,我知道问题不在我的json格式中,而是在我的post请求中。该文档在 C# 上有示例,但在 Java 上没有,这是我正在使用的。
顺便说一下,json is 变量是一个字符串,以防相关。
有人可以指出我的 post 代码有什么问题吗?
发现我遗漏了什么。
在查看发送到 API 的内容后,我注意到 json 不是预期的格式。所以我做了一些研究,发现至少对我来说,设置 headers 内容类型是不够的,我还必须设置被设置为 HttpPost 的实体,为此,我必须更改这行代码:
StringEntity entity = new StringEntity(json);
对此:
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
更改后,请求开始按预期工作。
我正在使用 Java、Spring 引导和 Apache HttpClient 尝试发送 post 请求。可以在此处找到我尝试访问的资源的文档:
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 - 错误请求。在上面的交互式文档 link 中,当我 post 我的 Json 时,我收到了重复输入的错误,这是我所期望的,因为我发送的信息已经在数据库中。
由于交互式文档returns重复错误,我知道问题不在我的json格式中,而是在我的post请求中。该文档在 C# 上有示例,但在 Java 上没有,这是我正在使用的。
顺便说一下,json is 变量是一个字符串,以防相关。
有人可以指出我的 post 代码有什么问题吗?
发现我遗漏了什么。 在查看发送到 API 的内容后,我注意到 json 不是预期的格式。所以我做了一些研究,发现至少对我来说,设置 headers 内容类型是不够的,我还必须设置被设置为 HttpPost 的实体,为此,我必须更改这行代码:
StringEntity entity = new StringEntity(json);
对此:
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
更改后,请求开始按预期工作。