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

发布于 2024-12-06 16:12:31 字数 1094 浏览 1 评论 0原文

我正在尝试使用 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 ”方法,但应用程序在该行代码之后没有响应。与 Firefox 的 REST 客户端连接时一切正常。我想不通。谢谢!

I'm trying to connect to a webservice using Java and REST. This is what I've tried, and I get a 411 error.

   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");


}

I also tried " setFixedLengthStreamingMode " method, but the application wasn't responding after that line of code. Everything works fine when connecting with REST Client for firefox. I can't figure it out. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

物价感观 2024-12-13 16:12:31

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

You aren't writing anything to the body of the request. In that case the content length should be 0 and not 57

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文