如何设置内容长度REST请求 - 适用于Android

时间:2011-09-26 12:17:24

标签: java android web-services rest

我正在尝试使用Java和REST连接到Web服务。这是我尝试过的,我得到411错误。

   public static String getSiteToken(String host,String token) throws IOException, JSONException 
{
    host = host.replace("https://", "http://");
    URL url = new URL(host + "/tokens");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setUseCaches(false);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Authorization", token);
    conn.setRequestProperty("Content-Length", "57");
    //conn.setFixedLengthStreamingMode(57);
        conn.setRequestProperty("Connection","keep-alive");
    InputStream is = conn.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader rd = new BufferedReader(isr);
    JSONObject json = new JSONObject(rd.readLine());
    rd.close();
    conn.disconnect();
    return json.getString("token");


}

我也尝试了“setFixedLengthStreamingMode”方法,但应用程序在该行代码后没有响应。与REST客户端连接时,一切正常。我无法弄清楚。谢谢!

1 个答案:

答案 0 :(得分:0)

您没有在请求正文中写任何内容。在这种情况下,内容长度应为0而不是57