[英]Problem with spring RestTemplate POST request
Trying to make a post call on one of our servers, but getting 400 BAD_REQUEST all the time 尝试在我们的一台服务器上进行邮寄呼叫,但始终获得400 BAD_REQUEST
static void postUserToken()
{
final String url = "SERVER ADDRESS";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
MultiValueMap<String, String> requestBody= new LinkedMultiValueMap<>();
requestBody.add("userName", "TESTUSER");
requestBody.add("password", "TESTPASSWORD");
requestBody.add("auth", "secEnterprise");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(requestBody, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class );
System.out.println(response);
}
get request to the same address works, post request via Postman works fine with the same body and headers 将请求发送到相同的地址,通过邮递员发送请求,使用相同的正文和标题可以正常工作
what am I missing ? 我想念什么?
EDIT 编辑
calls from postman 邮递员的电话
POST /api/call/ HTTP/1.1
Host: SEREVERADDRESS:6405
Content-Type: application/json
Accept: application/json
User-Agent: PostmanRuntime/7.15.0
Cache-Control: no-cache
Postman-Token: token1,token2
Host: SEREVERADDRESS:6405
accept-encoding: gzip, deflate
content-length: 92
Connection: keep-alive
cache-control: no-cache
{
"password": "PASSWORD",
"auth": "secEnterprise",
"userName": "USER"
}
in response I get an object like this {"token":"longtoken"} 作为响应,我得到了一个像这样的对象{“ token”:“ longtoken”}
You are using a MultiValueMap
however the json you send from postman looks like a simple Map
. 您正在使用
MultiValueMap
但是从邮递员发送的json看起来像一个简单的Map
。
This will produce {"key1":["val1"]}
instead of {"key1":"val1"}
这将产生
{"key1":["val1"]}
而不是{"key1":"val1"}
The problem might be in the 问题可能出在
headers.setContentType(MediaType.APPLICATION_JSON);
Try using headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
尝试使用
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
or convert your data to a proper JSON. 或将您的数据转换为适当的JSON。
More on this: https://www.baeldung.com/rest-template (4.4. Submit Form Data) 有关更多信息,请访问: https : //www.baeldung.com/rest-template (4.4。提交表单数据)
As far as I understand the problem and since I do not know your rest call details, I provide below the approach you can try. 据我了解的问题,并且由于我不知道您的休息电话详细信息,我在下面提供了您可以尝试的方法。
Remove the following line. 删除以下行。
requestBody.add("auth", "secEnterprise");
Add the line 添加行
headers.setHeader("auth", "secEnterprise");
If you are using other version of Apache Http Client, you can use the following code snippet. 如果您正在使用其他版本的Apache Http Client,则可以使用以下代码段。
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("header-name" , "header-value");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.