Spring Security 如何在Sping Boot 中使用带有Bearer Token和form-data的Rest Template调用REST API

aemubtdh  于 12个月前  发布在  Spring
关注(0)|答案(1)|浏览(213)

我正在使用Postman调用一个rest API,它使用以下请求给出了一个成功的响应(200 OK),
方法:POST
授权=>类型:承载令牌=>令牌:saflsjdflj
Body => form-data => Key:companyId,Value:123456
但是当我在spring Boot 中使用rest模板调用这个API时,它给出了400个错误请求。代码如下所示,

HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + token);

HashMap<String, String> requestBody = new HashMap<>();
requestBody.put("companyId", "123456");

HttpEntity requestEntity = new HttpEntity<>(requestBody, headers)

ResponseEntity<CompanyResponse> response = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, CompanyResponse.class);

字符串

ef1yzkbh

ef1yzkbh1#

您必须配置restTemplate:add FormHttpMessageConverter

RestTemplate restTemplate = new RestTemplateBuilder()
                .messageConverters(
                        new MappingJackson2HttpMessageConverter(objectMapper()),
                        new FormHttpMessageConverter())
                .build()

字符串
在发送请求时,必须将MediaType.APPLICATION_FORM_URLENCODED设置为contentType,并使用MultiValueMap而不是HashMap作为请求体:

HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + token);
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
requestBody.put("companyId", "123456");

HttpEntity requestEntity = new HttpEntity<>(requestBody, headers)

ResponseEntity<CompanyResponse> response = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, CompanyResponse.class);

相关问题