[英]content-length in HttpURLConnection
I'm trying to send a body in x-www-form-urlencoded
to my local Web API. 我正在尝试将
x-www-form-urlencoded
的正文发送到我的本地Web API。 I can make GET
without any problems. 我可以
GET
进行GET
。 Here is what I do: 这是我的工作:
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 promised 598 bytes, but received 0
java.net.ProtocolException:内容长度承诺为598个字节,但收到0
So it means that I'm not sending any data in my POST
, how come? 因此,这意味着我没有在
POST
发送任何数据,为什么呢?
Using con.setRequestProperty("Content-Length", Integer.toString(postDataLength));
使用
con.setRequestProperty("Content-Length", Integer.toString(postDataLength));
you're just sending the lenght of your postDataLength
, you're not actually setting it's body. 您只是发送了
postDataLength
的长度,实际上并没有设置它的主体。 In order to actually send your variable to the webservice you need to do this before calling the connect()
: 为了将变量实际发送到Web服务,您需要在调用
connect()
之前执行此操作:
OutputStream os = con.getOutputStream();
os.write(urlParameters.getBytes("UTF-8"));
os.close();
You need do this: 您需要这样做:
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.