簡體   English   中英

HttpURLConnection中的content-length

[英]content-length in HttpURLConnection

我正在嘗試將x-www-form-urlencoded的正文發送到我的本地Web API。 我可以GET進行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:內容長度承諾為598個字節,但收到0

因此,這意味着我沒有在POST發送任何數據,為什么呢?

使用con.setRequestProperty("Content-Length", Integer.toString(postDataLength)); 您只是發送了postDataLength的長度,實際上並沒有設置它的主體。 為了將變量實際發送到Web服務,您需要在調用connect()之前執行此操作:

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

您需要這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM