我正在尝试将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
发送任何数据,为什么会这样?
答案 0 :(得分:1)
使用con.setRequestProperty("Content-Length", Integer.toString(postDataLength));
你只是发送postDataLength
的长度,你实际上并没有设置它的身体。为了实际将您的变量发送到Web服务,您需要在调用connect()
之前执行此操作:
OutputStream os = con.getOutputStream();
os.write(urlParameters.getBytes("UTF-8"));
os.close();
答案 1 :(得分:0)
您需要执行以下操作:
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"));