|
| 1 | +### Using Spring RESTTemplate to Post Objects to RESTful web services that has Authentication with Spring's Java Configuration (JavaConfig) style with Maven, JUnit, Log4J |
| 2 | + |
| 3 | + |
| 4 | +In this example I am going to show you how to post data to a RESTful web service in Java using Spring, Spring Java Configuration and more |
| 5 | + |
| 6 | + |
| 7 | +### Web Service Code |
| 8 | + |
| 9 | +Let's take a quick look at the Spring MVC Web Service code on the server: |
| 10 | + |
| 11 | + @Controller |
| 12 | + @RequestMapping("/api") |
| 13 | + class JSonController |
| 14 | + { |
| 15 | + |
| 16 | + private static final Logger logger = LoggerFactory.getLogger(JSonController.class); |
| 17 | + |
| 18 | + |
| 19 | + |
| 20 | + @RequestMapping(value = "/{id}", method = RequestMethod.POST) |
| 21 | + @ResponseBody |
| 22 | + public User updateCustomer(@PathVariable("id") String id, @RequestBody User user) { |
| 23 | + |
| 24 | + logger.debug("I am in the controller and got ID: " + id.toString()); |
| 25 | + logger.debug("I am in the controller and got user name: " + user.toString()); |
| 26 | + |
| 27 | + return new User("NEW123", "NEW SMITH"); |
| 28 | + } |
| 29 | + |
| 30 | + |
| 31 | +As you can see from the code above the web service is goign to what for a ID and user object to be passed in and then its going to create a new User Object and send it back to the client. |
| 32 | + |
| 33 | +### Time For The Client Code |
| 34 | + |
| 35 | +You can see from the client code below is that we are using Spring RESTTemaple and going to post an User Object to a web server and get one back. |
| 36 | + |
| 37 | + |
| 38 | + @PropertySource("classpath:application.properties") |
| 39 | + public class Main |
| 40 | + { |
| 41 | + |
| 42 | + /** |
| 43 | + * Setting up logger |
| 44 | + */ |
| 45 | + private static final Logger LOGGER = getLogger(Main.class); |
| 46 | + |
| 47 | + |
| 48 | + public static void main(String[] args) throws IOException |
| 49 | + { |
| 50 | + LOGGER.debug("Starting REST Client!!!!"); |
| 51 | + |
| 52 | + /** |
| 53 | + * |
| 54 | + * This is going to setup the REST server configuration in the applicationContext |
| 55 | + * you can see that I am using the new Spring's Java Configuration style and not some OLD XML file |
| 56 | + * |
| 57 | + */ |
| 58 | + ApplicationContext context = new AnnotationConfigApplicationContext(RESTConfiguration.class); |
| 59 | + |
| 60 | + /** |
| 61 | + * |
| 62 | + * We now get a RESTServer bean from the ApplicationContext which has all the data we need to |
| 63 | + * log into the REST service with. |
| 64 | + * |
| 65 | + */ |
| 66 | + RESTServer mRESTServer = context.getBean(RESTServer.class); |
| 67 | + |
| 68 | + /** |
| 69 | + * |
| 70 | + * Setting up BASIC Authentication access |
| 71 | + * |
| 72 | + */ |
| 73 | + |
| 74 | + HttpClient client = new HttpClient(); |
| 75 | + UsernamePasswordCredentials credentials = |
| 76 | + new UsernamePasswordCredentials(mRESTServer.getUser(), mRESTServer.getPassword()); |
| 77 | + |
| 78 | + client.getState().setCredentials( |
| 79 | + new AuthScope(mRESTServer.getHost(), 8080, AuthScope.ANY_REALM), |
| 80 | + credentials); |
| 81 | + |
| 82 | + CommonsClientHttpRequestFactory commons = new CommonsClientHttpRequestFactory(client); |
| 83 | + |
| 84 | + |
| 85 | + |
| 86 | + /** |
| 87 | + * |
| 88 | + * Setting up data to be sent to REST service |
| 89 | + * |
| 90 | + */ |
| 91 | + Map<String, String> vars = new HashMap<String, String>(); |
| 92 | + vars.put("id", "INID"); |
| 93 | + |
| 94 | + /** |
| 95 | + * |
| 96 | + * Doing the REST call and then displaying the data/user object |
| 97 | + * |
| 98 | + */ |
| 99 | + try |
| 100 | + { |
| 101 | + |
| 102 | + /* |
| 103 | + |
| 104 | + This is code to post and return a user object |
| 105 | + |
| 106 | + */ |
| 107 | + |
| 108 | + RestTemplate rt = new RestTemplate(commons); // Added the CommonsClientHttpRequestFactory |
| 109 | + |
| 110 | + rt.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); |
| 111 | + rt.getMessageConverters().add(new StringHttpMessageConverter()); |
| 112 | + |
| 113 | + String uri = new String("http://" + mRESTServer.getHost() + ":8080/springmvc-resttemplate-auth-test/api/{id}"); |
| 114 | + |
| 115 | + User u = new User(); |
| 116 | + u.setName("Johnathan M Smith"); |
| 117 | + u.setUser("JMS"); |
| 118 | + |
| 119 | + |
| 120 | + User returns = rt.postForObject(uri, u, User.class, vars); |
| 121 | + |
| 122 | + LOGGER.debug("User: " + u.toString()); |
| 123 | + |
| 124 | + } |
| 125 | + catch (HttpClientErrorException e) |
| 126 | + { |
| 127 | + /** |
| 128 | + * |
| 129 | + * If we get a HTTP Exception display the error message |
| 130 | + */ |
| 131 | + |
| 132 | + LOGGER.error("error: " + e.getResponseBodyAsString()); |
| 133 | + |
| 134 | + ObjectMapper mapper = new ObjectMapper(); |
| 135 | + ErrorHolder eh = mapper.readValue(e.getResponseBodyAsString(), ErrorHolder.class); |
| 136 | + |
| 137 | + LOGGER.error("error: " + eh.getErrorMessage()); |
| 138 | + |
| 139 | + } |
| 140 | + catch(Exception e) |
| 141 | + { |
| 142 | + LOGGER.error("error: " + e.getMessage()); |
| 143 | + |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + } |
| 148 | + |
| 149 | + |
| 150 | +You can see from the above code how easy it is to use RESTTeample to post data to a web service. |
| 151 | + |
| 152 | + |
| 153 | + |
| 154 | +You can see how easy it is to use Spring's Java Configuration (JavaConfig) style and Not XML.. The time of using XML files with Springs is over... |
| 155 | + |
| 156 | +### We Can I Get The Sourcec Code |
| 157 | + |
| 158 | +You can checkout the project from github. |
| 159 | + |
| 160 | + git clone [email protected]:JohnathanMarkSmith/springmvc-resttemplate-auth-test.git |
| 161 | + cd springmvc-resttemplate-auth-test.git |
| 162 | + |
| 163 | + |
| 164 | +If you have any questions please email me at [email protected] |
0 commit comments