Java HttpURLConnection:内容长度计算

f4l*_*lco 7 java rest http urlconnection httpurlconnection

我正在为bitbucket开发一个用于发布RESTful API的库.我取得了很好的进展,现在我要解决需要HTTP PUT请求的更新问题部分.

现在我因为HTTP错误代码而陷入困境411 Length Required.经过一番谷歌搜索后,我发现了以下代码示例:

// CORRECT: get a UTF-8 encoded byte array from the response
// String and set the content-length to the length of the
// resulting byte array.
String response = [insert XML with UTF-8 characters here];
byte[] responseBytes;
try {
    responseBytes = response.getBytes("UTF-8");
}
catch ( UnsupportedEncodingException e ) {
    System.err.print("My computer hates UTF-8");
}

this.contentLength_ = responseBytes.length;
Run Code Online (Sandbox Code Playgroud)

现在我的问题是:究竟测量了什么?

  • 查询字符串
  • urlencoded查询字符串
  • 只有参数的值...... ??

并且是connection.setRequestProperty("Content-Length", String.valueOf(<mycomputedInt>));一种设置内容长度属性的适当方式?

举例赞赏.提前致谢.


编辑:

例如,您可以使用bitbucket wiki条目中的以下curl示例来解释计算:

curl -X PUT -d "content=Updated%20Content" \
https://api.bitbucket.org/1.0/repositories/sarahmaddox/sarahmaddox/issues/1/
Run Code Online (Sandbox Code Playgroud)

web*_*rap 7

你正在做请求,对.content-length是请求正文的字节数.在你的情况下

int content-length = "content=Updated%20Content".getBytes("UTF-8").length;
Run Code Online (Sandbox Code Playgroud)

究竟测量了什么?

url编码的查询字符串(在请求/实体主体中时)

  • 请不要在不指定字符集的情况下使用`getBytes`方法. (2认同)