我将如何使用Spring / Java中的Rest Template发布到REST服务

时间:2015-03-12 14:44:38

标签: java spring oauth resttemplate

卷曲'https://polestar-pay/oauth2/token'-H'接受编码:gzip,收缩'-H'内容类型:application / x-www-form-urlencoded'-H'接受: / ' - H'连接:keep-alive' - data'code = Jf5wPTklRviNEhC_QbCobA& client_id =<>& client_secret =<>& grant_type = authorization_code& state = a1b2c3d4' - 压缩

这里我试图用java编程来解决这个问题。

 @RequestMapping("/token")

public String listUsers1121(HttpServletRequest request1)throws IOException {

    String code = request1.getParameter("code");
    String state = request1.getParameter("state");
     RestTemplate restTemplate = new RestTemplate();
     String url="https://persona.paytm.com/oauth2/token"; 
  MultiValueMap<String, String> map = new LinkedMultiValueMap<String,String();
  map.add("client_id", "api-int");
  map.add("client_secret", "251b2340185643ac7522ceee74287b5b");
  map.add("grant_type", "authorization_code");
  map.add("code", code);
  map.add("state", state);


   HttpHeaders headers = new HttpHeaders();

    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      headers.set("Accept-Encoding","gzip,deflate");



    HttpEntity<MultiValueMap<String, String>> request =
new HttpEntity<MultiValueMap<String, String>>(map, headers);

 List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    messageConverters.add(new FormHttpMessageConverter());
   messageConverters.add(new MappingJacksonHttpMessageConverter());
   restTemplate.setMessageConverters(messageConverters);

   LoginResponse response = (LoginResponse) restTemplate.postForObject(url,   request, LoginResponse.class);    


      System.out.println(response.loginToken);
    System.out.println(response.toString());
     System.out.println(request.getBody().toString());
    System.out.println(request.getHeaders());
     return response.toString();

       }

使用Curl我得到了所需的响应(json输出),但通过这个我得到错误。我在下面的代码中做错了什么?

0 个答案:

没有答案