在 Spring 框架 resttemplate 中将请求 header content-type 设置为 json

Setting request header content-type to json in Spring Framework resttemplate

我正在学习 Spring 框架来创建使用基本身份验证和交换的 REST Web 服务的客户端 JSON。在网络上进行了大量搜索后,我编写了一些有效的代码(如下),但现在我收到了 "Unsupported Media Type" 错误,因为请求是使用 Content-Type text/plain 而不是 application/json。我在网络上没有发现任何内容显示如何在请求 header 中设置 Content-Type(不会完全迷失在杂草中)。我的代码是:

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

...

BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("login", "password"));
HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

RestTemplate restTemplate = new RestTemplate(requestFactory);
String url = "http://host:8080/path/";
String postBody = getPostInput("filename");
jsonString = restTemplate.postForObject(path, postBody, String.class);

任何指导将不胜感激。

谢谢, 乔治

您可以尝试使用以下代码中的任何方法

1

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entity = new HttpEntity<String>(postBodyJson ,headers);
restTemplate.put(uRL, entity);

2

RequestEntity<String> requestEntity = RequestEntity .post(new URL(attributeLookupUrl).toURI()) .contentType(MediaType.APPLICATION_JSON) .body(postBodyJson); 
restTemplate.exchange(requestEntity, responseClass);

3

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

// if you need to pass form parameters in request with headers.
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("username", userName);
map.add("password", password);

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<TokenVO> responses = restTemplate.postForEntity(URL, request, responseClass);