Search code examples
javajsonxbmc

Does anyone have an updated example on posting a JSON request?


I am having a mess of a time finding up to date information on sending a JSON request to a local server. I keep coming across examples that use deprecated code, and I'd really like to do this with code that isn't.

I can at least say that I now have a working example, and I am not receiving any deprecated messages from NetBeans, but I would like to know if what I've put together is the right way:

public void sendUpdateRequest() {
    String updateString = 
            "{\"jsonrpc\": \"2.0\", \"method\": \"VideoLibrary.Scan\"}" ;
    StringEntity entity = new StringEntity(updateString, Consts.UTF_8);
    HttpPost httpPost = new HttpPost(getURL()); // http://xbmc:xbmc@10.0.0.151:8080/jsonrpc
    entity.setContentType("application/json");
    httpPost.setEntity(entity);
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        HttpResponse response = client.execute(httpPost);
        System.out.println(response.getStatusLine()); // move to log
    }
    catch (IOException e) {
        e.printStackTrace(); // move to log
    }
}

This is something I'm working on to update XBMC with a JSON HTTP request

Edit

Changed the code to try with resources per the comment -- hopefully this will be useful for someone else dealing with JSON and Java


Solution

  • but I would like to know if what I've put together is the right way:

    Yes, you are doing it correctly given the details you've posted.

    The StringEntity contains the body of the request. You can set any appropriate headers there. Any other headers can be set directly on the HttpPost object.

    As stated in the comments, don't take any chances, close() the CloseableHttpClient in a finally block.