我尝试使用Spring RequestTemplate发送帖子请求,但我总是收到401错误;
使用curl
C:\Users\Latitude E 5410>curl -X POST http://localhost:8080/demo.rest.springsecu
rity.oauth2.0.authentication/oauth/token -H "Accept: application/json" -d "usern
ame=user1&password=user1&client_id=client1&client_secret=client1&grant_type=pass
word&scope=read,write"
{"access_token":"abe9d772-cb29-4bd7-b41a-437e50c10652","token_type":"bearer","re
fresh_token":"bc24f370-fcd8-4ae0-b724-a4241c746b29","expires_in":299844,"scope":
"read,write"}curl: (6) Could not resolve host: application
使用的java代码:
HttpEntity<String> request = new HttpEntity<String>(getHeadersWithClientCredentials());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON); //restTemplate.postForObject
//restTemplate.
MultiValueMap<String, String> mvm = new LinkedMultiValueMap<String, String>();
mvm.add("client_id", "client1");
mvm.add("client_secret", "client1");
mvm.add("grant_type", "password");
mvm.add("scope", "read,write,trust");
mvm.add("username", "user1");
mvm.add("password", "user1");
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(mvm, requestHeaders);
ResponseEntity<Object> response = restTemplate.exchange("http://localhost:8080/demo.rest.springsecurity.oauth2.0.authentication/oauth/token?", HttpMethod.POST, requestEntity, Object.class);
错误我
Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 401 Non-Autorisé
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:475)
at com.geofleet.calculation.TestClient.main(TestClient.java:44)
答案 0 :(得分:1)
我通过直接发送一个帖子请求找到了另一种解决方案,我仍然认为这样做是不好的做法(在网址中传递参数),但是嘿它有效,
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> s = restTemplate.exchange("http://localhost:8080/demo.rest.springsecurity.oauth2.0.authentication/oauth/token?username=user1&password=user1&client_id=client1&client_secret=client1&grant_type=password&scope=read", HttpMethod.POST, entity, String.class);
System.out.println(s.getBody().toString());