Post JSON Data from Java to WordPress WP API v2

I’m a bit stuck here and I don’t know why. It’s probably very simple. I want to post changes to a WordPress site from a Java app.

The following curl example does as it should:

Read More
curl -X POST -H "Content-Type: application/json" -d '{"title":"hello123"}' -u user:pass http://myurl.com/wp-json/wp/v2/posts/219 -v

The following code example not:

 try {
        URL url = new URL("http://myurl.com/wp-json/wp/v2/posts/219");
        String encoding = Base64.encodeBase64String((txtUserName.getText() + ":" + txtPassword.getText()).getBytes());

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Authorization", "Basic " + encoding);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("POST");
        connection.connect();

        ObjectMapper post = new ObjectMapper();
        ObjectNode node = post.createObjectNode();
        node.put("title", "test1234");

        OutputStream os = connection.getOutputStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(os, "UTF-8");
        outputStreamWriter.write(post.toString());
        outputStreamWriter.flush();
        outputStreamWriter.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

So I’m grateful for any help.

Thank you very much

Related posts