connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
The content type must match the actual format of the postData
. A content type of application/x-www-form-urlencoded
is only necessary if the content type is actually url encoded. E.g. you're encoding POST data as follows:
String data = "param1=" + URLEncoder.encode(param1, "UTF-8")
+ "¶m2=" + URLEncoder.encode(param2, "UTF-8");
This way the other side will be able to parse the data according the specified format without breaking it.
And,
connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
This is preferable to ensure a robust data transfer. If you omit this and the connection somehow get broken, then the other side will never be able to determine if the content is fully streamed in or not.
That said, the cast to HttpUrlConnection
is unnecessary if you know the fact that the request method will "automatically" be set to POST
if you do:
connection.setDoOutput(true);
or in your case more suitable:
connection.setDoOutput("POST".equals(method));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…