java - Atlassian汇合: how do I update page using REST API

标签 java confluence confluence-rest-api

我正在尝试使用以下代码更新 Confluence 页面: https://bitbucket.org/jaysee00/confluence-rest-api-example/src/master/src/main/java/com/atlassian/api/examples/Main.java

代码是:

public class Confluence {
/**
 * Demonstrates how to update a page using the Conflunence 5.5 REST API.
 */
private static final Logger LOGGER = Logger.getLogger(Confluence.class);;
private static final String BASE_URL = "http://confluence:8080";
private static final String USERNAME = "admin";
private static final String PASSWORD = "admin";
private static final String ENCODING = "utf-8";

private String getContentRestUrl(Long contentId, String[] expansions)
        throws UnsupportedEncodingException {
    String expand = URLEncoder.encode(StringUtils.join(expansions, ","),
            ENCODING);

    return String
            .format("%s/rest/api/content/%s?expand=%s&os_authType=basic&os_username=%s&os_password=%s",
                    BASE_URL, contentId, expand,
                    URLEncoder.encode(USERNAME, ENCODING),
                    URLEncoder.encode(PASSWORD, ENCODING));
}

public void publish() throws ClientProtocolException, IOException,   Exception {
    final long pageId = 36307446;

    HttpClient client = new DefaultHttpClient();

    // Get current page version
    String pageObj = null;
    HttpEntity pageEntity = null;
    try {
        String restUrl = getContentRestUrl(pageId,
                new String[] { "body.storage", "version", "ancestors" });
        HttpGet getPageRequest = new HttpGet(restUrl);
        HttpResponse getPageResponse = client.execute(getPageRequest);
        pageEntity = getPageResponse.getEntity();

        pageObj = IOUtils.toString(pageEntity.getContent());

        LOGGER.info("Get Page Request returned "
                + getPageResponse.getStatusLine().toString());
        LOGGER.info(pageObj);
        LOGGER.info((int)pageObj.trim().charAt(0));
    } finally {
        if (pageEntity != null) {
            EntityUtils.consume(pageEntity);
        }
    }

    // Parse response into JSON
    JSONObject page = new JSONObject(pageObj.trim());

    // Update page
    // The updated value must be Confluence Storage Format
    // NOT HTML.
    page.getJSONObject("body").getJSONObject("storage")
            .put("value", "hello, world");

    int currentVersion = page.getJSONObject("version").getInt("number");
    page.getJSONObject("version").put("number", currentVersion + 1);

    // Send update request
    HttpEntity putPageEntity = null;

    try {
        HttpPut putPageRequest = new HttpPut(getContentRestUrl(pageId,
                new String[] {}));

        StringEntity entity = new StringEntity(page.toString());
        entity.setContentType("application/json");
        putPageRequest.setEntity(entity);

        HttpResponse putPageResponse = client.execute(putPageRequest);
        putPageEntity = putPageResponse.getEntity();

        System.out.println("Put Page Request returned "
                + putPageResponse.getStatusLine().toString());
        System.out.println("");
        System.out.println(IOUtils.toString(putPageEntity.getContent()));
    } finally {
        EntityUtils.consume(putPageEntity);
    }
}

}

响应始终为“HTTP 404 - 找不到页面”。我已将页面 ID 更改为我知道 Confluence 中存在的页面 ID。

当它尝试将响应解析为 JSON 对象时,会出现异常:

avvvaorg.json.JSONException: A JSONObject text must begin with '{' at character 1
at org.json.JSONTokener.syntaxError(JSONTokener.java:496)
at org.json.JSONObject.<init>(JSONObject.java:180)
at org.json.JSONObject.<init>(JSONObject.java:403)
at com.openet.report.publish.Confluence.publish(Confluence.java:74)
at com.openet.report.miner.ReportMiner.generateSummary(ReportMiner.java:268)
at com.openet.report.miner.ReportMiner.runReport(ReportMiner.java:251)
at com.openet.report.miner.ReportMiner.main(ReportMiner.java:138)

最佳答案

Confluence 4.3.1 不支持使用 REST 更新 confluence 页面。 API 更加有限: https://docs.atlassian.com/atlassian-confluence/REST/4.3.1/

但是,您可以使用 XML RPC 更新 confluence:

public void publish() throws IOException {
    DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    Date today = Calendar.getInstance().getTime(); 
    XWikiXmlRpcClient rpc = new XWikiXmlRpcClient(CONFLUENCE_URI);
    try {
        rpc.login(USER_NAME, PASSWORD);
        //The info macro would get rendered an info box in the Page
        Page page = new Page();
        page.setSpace("Some space");
        page.setTitle("Testing XML RPC calls in confluence_" + df.format(today));            
        //page.setContent(
        String s = String.format("||Heading 1||Heading 2||Heading 3||%s|col A1|col A2|col A3|", "\r\n");
        page.setContent(s);
        page.setParentId(PAGEID);            
        rpc.storePage(page);
        } catch (XmlRpcException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            // TODO Auto-generated catch block

}

这需要以下库:

import org.apache.xmlrpc.XmlRpcException;
import org.codehaus.swizzle.confluence.Page;
import org.w3c.dom.Document;
import org.xwiki.xmlrpc.XWikiXmlRpcClient;

请注意,这些库不在标准 Maven 存储库中。您必须更新您的存储库管理器(在我的例子中是 artifactory)以与 XWiki maven 存储库同步。您还需要在 Confluence 上正确配置服务 Rocket 插件 ( https://community.servicerocket.com/servicerocket/topics/the-license-could-not-be-verified-there-is-no-license-certificate-installed-for-customware-scaffolding-plugin-for-confluence )。

关于java - Atlassian汇合: how do I update page using REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31944935/

相关文章:

sql - 如何使用 'Scripted Field' 获取 'SQL for Confluence' 值?

azure - 已删除应用程序中的用户,因此 AAD SCIM 配置不会修改/创建用户,因为它仍然缓存为 AAD 中现有的。怎么去掉?

python - 在 Confluence API 中保留新行

swagger - 如何以编程方式将 Swagger API 文档发布到 Atlassian Confluence? (Swagger Confluence 工具和 Confluence REST API 的使用)

api - GO:Confluence API 未获取所有附件

java - 为什么要声明类的自静态实例

java - JSP/Servlet 设计问题 - 通过 JNDI 使请求/响应全局可用

java - 修改端点以接收 XML 文件

java - 得到一个虚拟的 slf4j 记录器?