最近使用RestTemplate發送post請求,遇到了很多問題,如轉換httpMessage失敗、中文亂碼等,調了好久才找到下面較為簡便的方法:
RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); JSONObject jsonObj = JSONObject.fromObject(params); HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers); String result = restTemplate.postForObject(url, formEntity, String.class);
如果直接使用在postForObject中把對象傳入很容易出現no suitable HttpMessageConverter found for request type的錯誤,建議直接先轉成字符串,見jsonObj.otString(),
網上有人說設置RestTemplate的HttpMessageConverter,試了一下要引入各種包。
另外要注意中文編碼問題,網上有人說StringHttpMessageConverter默認使用ISO-8859-1,要指定為UTF-8編碼,自己嘗試沒有成功,最后通過指定contentType的方式解決了。
http://liuxing.info/2015/05/21/RestTemplate實踐/
http://www.cnblogs.com/zemliu/archive/2013/07/28/3220517.html
/** * * This is going to setup the REST server configuration in the applicationContext * you can see that I am using the new Spring's Java Configuration style and not some OLD XML file * */ ApplicationContext context = new AnnotationConfigApplicationContext(RESTConfiguration.class); /** * * We now get a RESTServer bean from the ApplicationContext which has all the data we need to * log into the REST service with. * */ RESTServer mRESTServer = context.getBean(RESTServer.class); /** * * Setting up BASIC Authentication access * */ HttpClient client = new HttpClient(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(mRESTServer.getUser(), mRESTServer.getPassword()); client.getState().setCredentials( new AuthScope(mRESTServer.getHost(), 8080, AuthScope.ANY_REALM), credentials); CommonsClientHttpRequestFactory commons = new CommonsClientHttpRequestFactory(client); /** * * Setting up data to be sent to REST service * */ Map<String, String> vars = new HashMap<String, String>(); vars.put("id", "INID"); /** * * Doing the REST call and then displaying the data/user object * */ try { /* This is code to post and return a user object */ RestTemplate rt = new RestTemplate(commons); // Added the CommonsClientHttpRequestFactory rt.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); rt.getMessageConverters().add(new StringHttpMessageConverter()); String uri = new String("http://" + mRESTServer.getHost() + ":8080/springmvc-resttemplate-auth-test/api/{id}"); User u = new User(); u.setName("Johnathan M Smith"); u.setUser("JMS"); User returns = rt.postForObject(uri, u, User.class, vars); LOGGER.debug("User: " + u.toString());
https://github.com/JohnathanMarkSmith/springmvc-resttemplate-auth-test
/** * * This is going to setup the REST server configuration in the applicationContext * you can see that I am using the new Spring's Java Configuration style and not some OLD XML file * */ ApplicationContext context = new AnnotationConfigApplicationContext(RESTConfiguration.class); /** * * We now get a RESTServer bean from the ApplicationContext which has all the data we need to * log into the REST service with. * */ RESTServer mRESTServer = context.getBean(RESTServer.class); /** * * Setting up data to be sent to REST service * */ Map<String, String> vars = new HashMap<String, String>(); vars.put("id", "JS01"); /** * * Doing the REST call and then displaying the data/user object * */ try { /* This is code to post and return a user object */ RestTemplate rt = new RestTemplate(); rt.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); rt.getMessageConverters().add(new StringHttpMessageConverter()); String uri = new String("http://" + mRESTServer.getHost() + ":8080/springmvc-resttemplate-test/api/{id}"); User u = new User(); u.setName("Johnathan M Smith"); u.setUser("JS01"); User returns = rt.postForObject(uri, u, User.class, vars); LOGGER.debug("User: " + u.toString());
https://github.com/JohnathanMarkSmith/springmvc-resttemplate-test