Skip to content
This repository has been archived by the owner on Jan 21, 2024. It is now read-only.

Rest Client

DaviRyan edited this page Nov 4, 2014 · 34 revisions

#The SBT Rest Client The RestClient is a set of lightweight HTTP libraries for performing most types of HTTP requests. Features

  • GET, POST ,PUT and DELETE operations.
  • Handles JSON, XML, and Atom responses as well as String/Raw responses.
  • Supports URL parameters, file uploads and custom body entities.
  • Supports Basic Authentication.
  • Supports custom headers.

Set Up Your Project

You need the com.ibm.sbt.core.jar dependency. You can add this to your project by creating a maven project and listing the sbt.core.jar as a dependency or manually add the jar and its dependencies from the social business toolkit build.

Use The Rest Client

RestClient restClient = new RestClient("serverUrl","username","password"); Response<AtomFeed> responseFeed = restClient.doGet("/api/resource").asAtomFeed();

Or Statically RestClient.get("http://server/api/resource").basicAuth("username","password").asJson();

You can also create a client using an existing endpoint. BasicEndpoint endpoint = new BasicEndpoint(); endpoint.setUrl("http://serverUrl.com"); endpoint.setUser("username"); endpoint.setPassword("password"); RestClient client = new RestClient(endpoint);

Or you can create the RestClient using an endpoint defined in a ManagedBeans.xml file. RestClient restClient = new RestClient("IBMConnections");

Create Requests and Get Responses

To create a request using a static client call the clients get(), post(), put() or delete() methods or doGet(), doPost(), doPut() and doDelete() if using non statically. Then call one of the Data hadler methods to return the response. For example asString(), asXML(). Response<String> response = RestClient.get("Http://server.com/api/resource").asString();

##Add Parameters, Headers and Request Body To add a URL Parameter RestClient.get("Http://server.com/api/resource").parameter("email","[email protected]");

Or if you have multiple parameters you can create a map of parameters and add this to the request. Map<String, String> params = new HashMap<String, String>(); params.put("email", "[email protected]"); params.put("name", "frank adams"); RestClient.get("http://server/api/resource").parameters(params);

To add headers RestClient.get("Http://server.com/api/resource").header("Content-type","application/xml"); You can also add a map of headers in the same way as adding a map of parameters.

To add the request body, pass the body as a string as well as the Content Type. RestClient.post("http://server/api/resource").body(requestBody, "Application/XML");

##Add Basic Authentication RestClient.get("http://server/api/resource").basicAuth("username", "password");