http POST请求:curl和postman都成功了,但是resttemplate给出了400个错误请求



我正在尝试将curl(也证明在postman中工作)查询转换为java resttemplate:

$ curl -X POST https://my.server/apiv2/login -k  -H 'Accept: application/json' -H 'Content-Type: application/json' -d '{"password":"forgetme","userName":"myname"}'
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
Dload  Upload   Total   Spent    Left  Speed
100   593  100   492  100   101   1817    373 --:--:-- --:--:-- --:--:--  2196{"token":"sometoken",...}
然而,下面的代码给出了404错误
JSONObject payload = new JSONObject();
payload.put("userName", this.serviceAccount);
payload.put("password", this.password);
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
headers.add("Content-Type", MediaType.APPLICATION_JSON.toString());
HttpEntity<String> entity = new HttpEntity<String>(payload.toString(), headers);

ResponseEntity<Response> result =
this.restTemplate.exchange(tokenUrl.toString(), HttpMethod.POST, entity, Response.class);

我验证了url,用户名和密码都是正确的。

2022-05-14 04:04:03 [scheduling-1] ERROR  *** url =https://my.server/apiv2/login
2022-05-14 04:04:03 [scheduling-1] ERROR  *** entity = <{"password":"forgetme","userName":"myname"},[Accept:"application/json", Content-Type:"application/json"]>

唯一似乎相关的是,在实体中,application/json被双引号包围,如果我在application/json周围加上双引号,查询将失败(根本没有响应)

如果我将实体构造代码更改为

HttpEntity<JSONObject> entity = new HttpEntity<JSONObject>(payload, headers);

I will get 400 Bad Request exception

====================================================我不会张贴这个作为一个答案,直到我明白为什么。我设法使它工作通过初始化resttemplate如下:

HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setConnectTimeout(300000);
requestFactory.setReadTimeout(300000);
this.restTemplate = new RestTemplate(requestFactory);
this.restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
this.restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
this.restTemplate.setErrorHandler(new MyThrowErrorHandler());

public class MyThrowErrorHandler implements ResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return false;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
}

我知道它忽略了异常,但查询实际上是成功的,我得到了预期的响应。所以我现在的问题是,如果它确实是一个错误的请求,上面的额外代码如何修复错误的请求。

在这种情况下,您可以尝试调试有效负载。我使用https://req.dothttp.dev/预览请求的curl

将url替换为https://req.dothttp.dev/https://my.server/apiv1/login,并与curl语句进行比较。

相关内容

  • 没有找到相关文章