code_junkie

Rest clients for Java?

Nov 11th, 2011
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. clientConfig = new DefaultClientConfig();
  2. client = Client.create(clientConfig);
  3.  
  4. resource = client.resource("http://localhost:8080");
  5. // lets get the XML as a String
  6. String text = resource("foo").accept("application/xml").get(String.class);
  7.  
  8. private void updateCustomer(Customer customer) {
  9. try {
  10. URL url = new URL("http://www.example.com/customers");
  11. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  12. connection.setDoOutput(true);
  13. connection.setInstanceFollowRedirects(false);
  14. connection.setRequestMethod("PUT");
  15. connection.setRequestProperty("Content-Type", "application/xml");
  16.  
  17. OutputStream os = connection.getOutputStream();
  18. jaxbContext.createMarshaller().marshal(customer, os);
  19. os.flush();
  20.  
  21. connection.getResponseCode();
  22. connection.disconnect();
  23. } catch(Exception e) {
  24. throw new RuntimeException(e);
  25. }
  26. }
  27.  
  28. WebResource resource = client.resource("http://www.example.com/customers");
  29. ClientResponse response = resource.type("application/xml");).put(ClientResponse.class, "<customer>...</customer.");
  30. System.out.println(response);
  31.  
  32. // Make a GET request to "/lotto"
  33. String json = get("/lotto").asString()
  34. // Parse the JSON response
  35. List<String> winnderIds = with(json).get("lotto.winners.winnerId");
  36.  
  37. // Make a POST request to "/shopping"
  38. String xml = post("/shopping").andReturn().body().asString()
  39. // Parse the XML
  40. Node category = with(xml).get("shopping.category[0]");
Add Comment
Please, Sign In to add comment