spring - 在 Spring Framework resttemplate 中将请求 header 内容类型设置为 json

标签 spring rest content-type resttemplate

我正在学习 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/

相关文章:

java - 将内容(url)包含到 jsp 中

java - 与应用程序隔离的 WildFly9 JASPI 模块

spring - 使用Maven更新Spring框架版本后Eclipse的Tomcat Server无法启动

javascript - 如何在 Javascript 中获取给定 url 的内容类型?

actionscript-3 - 无法在as3中为URLRequest设置 "Content-Type"

java - 如何使用 spring-boot 注入(inject) Map<Object, List<Object>> ?

java - 在 spring rest Api 中启用 SSL (HTTPS)

java - 具有参数 PersistentEntityResourceAssembler 的 RestController 的 JUnit

http - 用于开发 RESTful Web 服务的工具

grails - 在Grails中渲染具有自定义mime类型的 View