我正在学习Spring Framework来创建一个REST Web服务的客户端,该服务使用基本身份验证并交换JSON。经过网上搜索,我编写了一些有用的代码(下图),但现在我收到了“不支持的媒体类型”错误,因为请求是使用Content-Type text / plain而不是application / json发送的。我在网上找不到任何显示如何在请求标题中设置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);
非常感谢任何指导。
谢谢, 乔治
答案 0 :(得分:52)
您可以尝试使用以下代码中的任何方法
<强> 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);