2015-04-02 69 views
7

我在学习Spring框架以创建使用基本认证和交换JSON的REST Web服务的客户端。在网络上进行了大量搜索之后,我编写了一些可以工作的代码(如下),但现在我得到了“不支持的介质类型”错误,因为请求是使用Content-Type text/plain而不是application/json发送的。我没有在Web上发现任何内容,显示如何在请求头中设置Content-Type(没有完全丢失杂草)。我的代码是:在Spring框架resttemplate中将请求标头内容类型设置为json

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); 

任何指导将不胜感激。

感谢, 乔治

+0

我意识到一些代码是不正确的。我正在发送带有JSON正文的POST请求。这是正确的代码。 – user2752012 2015-04-02 16:07:00

+0

我编辑了原始问题以更正代码。仍在学习如何使用计算器... – user2752012 2015-04-02 16:13:28

+0

帮助吗? http://stackoverflow.com/questions/10263854/java-httpclient-changing-content-type – 2015-04-02 16:15:45

回答

21

您可以尝试使用下面的代码

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

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