我正在学习 Spring Framework 以创建使用基本身份验证和交换 JSON 的 REST Web 服务的客户端。在网络上进行大量搜索后,我编写了一些有效的代码(如下),但现在我收到“不支持的媒体类型”错误,因为请求是使用 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);
关于spring - 在 Spring Framework resttemplate 中将请求 header 内容类型设置为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29417455/