Monday, February 13, 2012

XML-RPC WordPress client in Java

This code is an XML-RPC WordPress client written in Java. Note that you must first enable XML-RPC on your WordPress site which is under Settings > Write > Remote Publishing. Note also that you require xmlrpc-client-3.1.3.jar, xmlrpc-common-3.1.3.jar and ws-commons-util-1.0.2.jar on your classpath. These jar files can be found in the Apache XML-RPC distributable which is available in the mvnrepository if the Apache mirrors are unavailable. The WordPress website shows the full list of methods available.

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Hashtable;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;


public class WordPressClient
{
 private static final String USERNAME = "username";
 private static final String PASSWORD = "password";
 private static final int BLOG_ID = 1;
 private static final String URL = "http://example.com/xmlrpc.php";


 public static void main(String[] args) throws Exception
 {
  System.out.println("Connecting to: " + URL);

  final XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
  config.setServerURL(new URL(URL));

  final XmlRpcClient client = new XmlRpcClient();
  client.setConfig(config);

  final Hashtable content = new Hashtable();
  content.put("wp_page_parent_id", 11);
  content.put("title", "Page Title");
  content.put("description", "Description goes here. You can use <b>some HTML markup</b>.");
  final boolean publish = true;

  final Object[] params = new Object[] { BLOG_ID, USERNAME, PASSWORD, content, publish };
  final Object result = client.execute("wp.newPage", params);
  final int pageId = Integer.parseInt(result.toString());

  System.out.println("Successful! New page ID is " + pageId);
 }
}

2 comments:

  1. Replies
    1. Weird... the Apache mirror sites all give HTTP 404 errors. You can still get the .jar files from Maven though - see the new link in the article.

      Delete