在我的应用程序中,我正在尝试使用 POST 请求获取响应。响应服务器以 Json 格式发送给我。但在添加属性后,它返回我的响应代码为 411(即内容长度问题)。我已经添加了内容长度。那么我没有得到的问题在哪里。这是我的代码:
String url = "https://xxx:8243/people/v3";
STRURL = url + HttpComm.getConnectionString().trim();
StringBuffer postData = new StringBuffer();
HttpConnection httpConnection = null;
try {
httpConnection = (HttpConnection) Connector.open(STRURL);
} catch (IOException e1) {
e1.printStackTrace();
};
try {
httpConnection.setRequestMethod("POST");
postData.append("?username="+user);
postData.append("&password="+password);
String encodedData = postData.toString();
byte[] postDataByte = postData.toString().getBytes("UTF-8");
httpConnection.setRequestProperty("Authorization", "bearer"+"ZWOu3HL4vwaOLrFAuEFqsxNQf6ka");
httpConnection.setRequestProperty("Content-Type","application/json");
httpConnection.setRequestProperty("Content-Length", String.valueOf(postDataByte.length));
OutputStream out = httpConnection.openOutputStream();
DataOutputStream dos = new DataOutputStream(out);
out.write(postData.toString().getBytes());
out.flush();
int statusCode = httpConnection.getResponseCode();
Logger.out("HttpComm", "status code::::::: "+statusCode);
if (statusCode != HttpConnection.HTTP_OK)
{
}
更新代码:
HttpConnection httpConnection = null;
try {
httpConnection = (HttpConnection) Connector.open(STRURL);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
try {
httpConnection.setRequestMethod("POST");
URLEncodedPostData postData = new URLEncodedPostData("UTF-8", false);
postData.append("username", user);
postData.append("password", password);
byte[] postDataByte = postData.getBytes();
httpConnection.setRequestProperty("Authorization", "bearer"+"ZWOu3HL4vwaOLrFAuEFqsxNQf6ka");
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestProperty("Content-Length", String.valueOf(postDataByte.length));
OutputStream out = httpConnection.openOutputStream();
out.write(postDataByte);
out.flush();
int statusCode = httpConnection.getResponseCode();
Logger.out("HttpComm", "status code::::::: "+statusCode);