IBM MobileFirst Java HTTP Adapter
IBM MobileFirst Java HTTP Adapter
HTTP Client
private static CloseableHttpClient client;
private static HttpHost host;
public static void init() {
client = HttpClientBuilder.create().build();
host = new HttpHost("mobilefirstplatform.ibmcloud.com");
}
Because every request to your resource will create a new instance of JavaHTTPResource , it is important
to reuse objects that may impact performance. In this example we made the Http client a static object
and initialized it in a static init() method, which gets called by the init() of JavaHTTPApplication as
described above.
Procedure resource
@GET
@Produces("application/json")
public void get(@Context HttpServletResponse response, @QueryParam("tag") String tag)
throws IOException, IllegalStateException, SAXException {
if(tag!=null && !tag.isEmpty()){
execute(new HttpGet("/blog/atom/"+ tag +".xml"), response);
}
else{
execute(new HttpGet("/feed.xml"), response);
}
}
The sample adapter exposes just one resource URL which allows to retrieve the RSS feed from the
backend service.
@GET means that this procedure only responds to HTTP GET requests.
@Produces("application/json") specifies the Content Type of the response to send back. We
chose to send the response as a JSON object to make it easier on the client-side.
@Context HttpServletResponse response will be used to write to the response output stream.
code is responsible for handling potential exceptions which will be received as HTTP 500 errors.
Another solution (more likely in production code) is to handle exceptions in your server Java code
and decide what to send to the client based on the exact error.
execute(new HttpGet("/feed.xml"), response) . The actual HTTP request to the backend
execute()
Sample adapter
Click to download (https://github.com/MobileFirst-Platform-Developer-Center/Adapters/tree/release80) the
Adapters Maven project.
The Adapters Maven project includes the JavaHTTP adapter described above.
Sample usage
Use either Maven, MobileFirst CLI or your IDE of choice to build and deploy the JavaHTTP adapter
(../../creating-adapters/).
To test or debug an adapter, see the testing and debugging adapters (../../testing-and-debuggingadapters) tutorial.