Search code examples
javarestpostrest-clientsitebricks

How to post body in sitebricks-client?


I am using sitebricks-client to interact with REST APIs in Java. I need to do a POST with a non-empty body. How do I do that in sitebricks?


Solution

  • You have not specified what kind of request body you are trying to post. If you are trying to send a String with a Content-Type of "text/plain", then the following should work:

    String body = "Request body.";
    WebResponse response = web.clientOf(url)
        .transports(String.class)
        .over(Text.class)
        .post(body);
    

    If you are trying to send data of a particular type that you have already serialized to a String, you can set the Content-Type header manually:

    String body = "{}";
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/json");
    WebResponse response = web.clientOf(url, headers)
        .transports(String.class)
        .over(Text.class)
        .post(body);
    

    If you have a Map containing data that you would like to send to the server with a Content-Type of "application/json", then something like this might be up your alley:

    Map body = new HashMap();
    // Fill in body with data
    WebResponse response = web.clientOf(url)
        .transports(Map.class)
        .over(Json.class)
        .post(body);
    

    There are two important points to pay attention to in the examples above:

    • The value passed to the post method should be of the type passed to the transports method.
    • The class that you pass to the over method determines the default value of the Content-Type header and the way in which the value passed to the post method is serialized. The class should be a subclass of com.google.sitebricks.client.Transport, and you will probably want to choose one of the classes found in the com.google.sitebricks.client.transport package.