Tob*_*obi 12 java spring spring-web
我是Spring的新手,并试图用RestTemplate做一个休息请求.Java代码应该像下面的curl命令一样:
curl --data "name=feature&color=#5843AD" --header "PRIVATE-TOKEN: xyz" "https://someserver.com/api/v3/projects/1/labels"
Run Code Online (Sandbox Code Playgroud)
但是服务器用一个拒绝RestTemplate 400 Bad Request
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("PRIVATE-TOKEN", "xyz");
HttpEntity<String> entity = new HttpEntity<String>("name=feature&color=#5843AD", headers);
ResponseEntity<LabelCreationResponse> response = restTemplate.exchange("https://someserver.com/api/v3/projects/1/labels", HttpMethod.POST, entity, LabelCreationResponse.class);
Run Code Online (Sandbox Code Playgroud)
谁能告诉我我做错了什么?
Nik*_*sev 24
我认为问题是当你尝试向服务器发送数据时没有设置内容类型标题,它应该是两个中的一个:"application/json"或"application/x-www-form-urlencoded".在您的情况下是:"application/x-www-form-urlencoded"基于您的样本参数(名称和颜色).此标头表示"客户端向服务器发送的数据类型".
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("PRIVATE-TOKEN", "xyz");
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("name","feature");
map.add("color","#5843AD");
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
ResponseEntity<LabelCreationResponse> response =
restTemplate.exchange("https://foo/api/v3/projects/1/labels",
HttpMethod.POST,
entity,
LabelCreationResponse.class);
Run Code Online (Sandbox Code Playgroud)
您需要将 Content-Type 设置为 application/json。必须在请求中设置 Content-Type。下面是修改后的代码来设置 Content-Type
final String uri = "https://someserver.com/api/v3/projects/1/labels";
String input = "US";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("PRIVATE-TOKEN", "xyz");
HttpEntity<String> request = new HttpEntity<String>(input, headers);
ResponseEntity<LabelCreationResponse> response = restTemplate.postForObject(uri, request, LabelCreationResponse.class);
Run Code Online (Sandbox Code Playgroud)
在这里,HttpEntity 是用您的输入(即“US”)和标头构造的。让我知道这是否有效,如果无效,请分享异常。干杯!
小智 7
这可能是一个标头问题,检查标头是否是有效标头,您指的是“BasicAuth”标头吗?
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED.toString());
headers.add("Accept", MediaType.APPLICATION_JSON.toString()); //Optional in case server sends back JSON data
MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<String, String>();
requestBody.add("name", "feature");
requestBody.add("color", "#5843AD");
HttpEntity formEntity = new HttpEntity<MultiValueMap<String, String>>(requestBody, headers);
ResponseEntity<LabelCreationResponse> response =
restTemplate.exchange("https://example.com/api/request", HttpMethod.POST, formEntity, LabelCreationResponse.class);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15589 次 |
| 最近记录: |