-
Notifications
You must be signed in to change notification settings - Fork 0
Rest Client
#The SBT Rest Client The RestClient is a lightweight HTTP library 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.
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.Below is the dependency you need to add to the POM.xml
`<dependency>`
`<groupId>com.ibm.sbt</groupId>`
`<artifactId>com.ibm.sbt.core</artifactId> `
`<version>1.1.0.20140717-1200</version>`
`</dependency> `
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");
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 handler 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");