【问题标题】:content-length in HttpURLConnectionHttpURLConnection 中的内容长度
【发布时间】:2017-12-01 13:26:48
【问题描述】:

我正在尝试将x-www-form-urlencoded 中的正文发送到我的本地 Web API。我可以毫无问题地制作GET。这是我的工作:

    String urlParameters = "user=User&label=GPU+Temp&file=src%2FDataSource0.txt&backgroundColor=rgb(255%2C255%2C255%2C0)&borderColor=rgb(255%2C255%2C255%2C0)&pointBorderColor=rgb(255%2C255%2C255%2C0)&pointHoverBackgroundColor=rgb(255%2C255%2C255%2C0)&pointHoverBorderColor=rgb(255%2C255%2C255%2C0)&min=0&max=100&stepSize=50";

    byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
    int postDataLength = postData.length;
    String request = "http://192.168.1.30:6262/api/values";
    URL url = new URL(request);
    con = (HttpURLConnection) url.openConnection();
    con.setDoOutput(true);
    con.setInstanceFollowRedirects(false);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestProperty("charset", "utf-8");
    con.setRequestProperty("Content-Length", Integer.toString(postDataLength));
    con.connect();

java.net.ProtocolException: content-length 承诺 598 字节,但收到 0

所以这意味着我没有在我的POST 中发送任何数据,怎么会?

【问题讨论】:

  • 你需要像 con.getOutputStream().write(postData) 一样发送你的 postData

标签: java android httpurlconnection content-length


【解决方案1】:

使用con.setRequestProperty("Content-Length", Integer.toString(postDataLength)); 只是发送postDataLength 的长度,实际上并没有设置它的主体。为了真正将您的变量发送到网络服务,您需要在调用 connect() 之前执行此操作:

OutputStream os = con.getOutputStream();
os.write(urlParameters.getBytes("UTF-8"));
os.close();

【讨论】:

  • 我认为,发送的正文是空的。谢谢你的时间。
  • @BeGreen 没问题!很高兴我能帮忙:)
【解决方案2】:

你需要这样做:

            body = datos.toString();
            content_bytes = body.getBytes("UTF-8");
            content_length = content_bytes.length;



            // establecer headers.
            connection.setRequestProperty( "Content-Type", "application/json; charset=utf-8" );
            connection.setRequestProperty( "Content-Length", Integer.toString( content_length  ) );

.....

            dataOutputStream = new DataOutputStream( connection.getOutputStream() );
            dataOutputStream.write(body.getBytes("UTF-8"));

【讨论】:

  • 嗨,欢迎来到 Stack Overflow!请edit您的回答详细说明此代码的工作原理以及它将如何解决问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-27
  • 2011-01-18
  • 2012-04-09
  • 1970-01-01
  • 2012-12-07
  • 1970-01-01
相关资源
最近更新 更多