何度やっても同じ

ただの日記

GAE/JでApache XML-RPCをつかう

Apache XML-RPC

そのまんま使おうとしたら案の定エラーが出たので、

の2点のみをApache XML-RPCにやらせて、HttpURLConnectionの操作は自分で行うことにした。
必要なライブラリは以下の3つ。xxxのところはバージョン番号ね。

  • ws-commons-util-xxx.jar
  • xmlrpc-client-xxx.jar
  • xmlrpc-common-xxx.jar

以下サンプルコード

import static org.apache.xmlrpc.common.XmlRpcStreamConfig.UTF8_ENCODING;

...

private static final XmlRpcClientConfigImpl CONFIG = new XmlRpcClientConfigImpl();
private static final TypeFactory TYPE_FACTORY = new TypeFactoryImpl(null);

@SuppressWarnings("unchecked")
public static Map<String, String> call(String url, String method, Object... params)
        throws IOException, XmlRpcException {

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setUseCaches(false);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.addRequestProperty("Content-Type", "text/xml");

    XmlRpcRequest req = new XmlRpcClientRequestImpl(CONFIG, method, params);

    OutputStream out = conn.getOutputStream();
    try {
        XmlRpcWriter xw = new XmlRpcWriter(CONFIG, getXmlHandler(out), TYPE_FACTORY);
        xw.write(req);
    } catch (SAXException e) {
        throw new XmlRpcClientException(e.getMessage(), e);
    } finally {
        out.close();
    }

    InputStream in = conn.getInputStream();
    XmlRpcResponseParser xp;
    try {
        xp = new XmlRpcResponseParser(CONFIG, TYPE_FACTORY);
        XMLReader xr = SAXParsers.newXMLReader();
        xr.setContentHandler(xp);
        xr.parse(new InputSource(in));
    } catch (SAXException e) {
        throw new XmlRpcClientException(e.getMessage(), e);
    } finally {
        in.close();
    }

    if (xp.isSuccess()) {
        return (Map<String, String>) xp.getResult();
    }

    Throwable t = xp.getErrorCause();
    if (t != null) {
        throw new XmlRpcException(t.getMessage(), t);
    } else {
        throw new XmlRpcException(xp.getErrorCode() + " : " + xp.getErrorMessage());
    }
}


private static ContentHandler getXmlHandler(OutputStream out) throws XmlRpcException {
    XMLWriter xw = new XMLWriterImpl();
    xw.setDeclarating(true);
    xw.setEncoding(UTF8_ENCODING);
    xw.setIndenting(false);
    xw.setFlushing(true);
    try {
        xw.setWriter(new BufferedWriter(new OutputStreamWriter(out, UTF8_ENCODING)));
    } catch (UnsupportedEncodingException e) {
        throw new InternalError();
    }
    return xw;
}