-
Notifications
You must be signed in to change notification settings - Fork 16
Accessing RESTful Services 1.2.3
Lahiru Sahan Jayasinghe edited this page Jan 1, 2014
·
1 revision
Endpoints may communicate with remote services which offer a RESTful architecture for interfacing.
Assume that the sample endpoint below uses a JSON parser definition at the type-level.
####1. Defining RESTful Methods
The usual @Request
annotation should be replaced with the @Rest
annotation which takes a sub-path and the HTTP method type associated with the request.
######Entity
public class Contact implements Serializable { private long id; private String username; private String mobile; /* serialVersionUID, Accessors, Mutators, * hashCode() and equals() omitted */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("{\\"id\\":"); builder.append(String.valueOf(this.id)); builder.append(", \\"username\\":\\""); builder.append(this.username); builder.append("\\", \\"mobile\\":\\""); builder.append(this.mobile); builder.append(\\"}); return builder.toString(); } }
To transform complex entities to JSON, use a cached instance of
Gson
.
######Definition ```java @Rest(path = "/contacts/update", method = RequestMethod.HTTP_POST) public abstract void updateContact(@Param("contact") Contact contact); ``` > Headers are populated the usual way using `@Header` and `@HeaderSet`. The default HTTP method is GET.
######Invocation ```java Contact doctorWho = endpoint.readContact("TheDoctor"); doctorWho.setMobile("201184919");
endpoint.update(doctorWho);
<br/><br/>
####2. Populating Path Parameters
Along with typical request parameters, the path to a RESTful resource may be parameterized as well. Such paths can be marked with <b>placeholders</b> to indicate the need for a parameter and supplied via variables annotated with the `@PathParam` annotation.
> Placeholders are created by prefixing a name with a colon.
<br/>
######Definition
```java
@Rest(path = "/contacts/read/:username")
public abstract Contact readContact(@PathParam("username") String username);
######Invocation
Contact riverSong = endpoint.readContact("RiverSong");