HTTP PUT请求Bitbucket API

时间:2011-06-23 16:19:36

标签: java http http-headers bitbucket

我想开发一个用于bitbucket问题API访问的java库 我已经问了一个关于the computation of the HTTP Content-Length header的问题,但这个问题具体是关于Bitbucket API和更新问题的过程(因为其他所有请求都运行良好)。

以下代码无效,发出411 Length Required错误 但更令人困惑的是:在文档中,您被告知使用PUT请求方法。如果您“忘记”指定,状态代码将更改为200 OK,但保持问题不变。

public class PutTest {
    public static void main(String[] args) throws Exception {
        URL u = new URL("https://api.bitbucket.org/1.0/repositories/myname/myproject/issues/1/?title=hello+world");
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.addRequestProperty("Authorization", "Basic "+Base64.encodeToString("user:password".getBytes(), false));
        c.addRequestProperty("Content-Length", String.valueOf(u.getQuery().getBytes("UTF-8").length));
        c.setRequestMethod("PUT");
        c.connect();
        System.out.println(c.getResponseCode()+" "+c.getResponseMessage());
    }
}

1 个答案:

答案 0 :(得分:1)

我的更新代码示例在stackoverflow的另一个问题的帮助下工作:How to send PUT, DELETE HTTP request in HttpURLConnection? Looks like not working

利用连接的OutputStream可以正常工作。

public class PutTest {

    public static void main(String[] args) throws Exception {
        URL u = new URL("https://api.bitbucket.org/1.0/repositories/myname/myproject/issues/1/");
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.addRequestProperty("Authorization", "Basic "+Base64.encodeToString(("user:password").getBytes(), false));
        c.setRequestMethod("PUT");
        c.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream());
        out.write("title=hello+world");
        out.close();
        c.connect();
        System.out.println(c.getResponseCode()+" "+c.getResponseMessage());
    }
}