我正在此处查看文档:http://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html
我没有看到将请求标记为 POST 方法的选项。我希望看到.setRequestMethod("POST");
或者其他的东西。我是否看错了文档?
我使用的是 Android 4.2 和 Java 1.6。虽然我不确定是否 javase/1.4.2
这就是我应该寻找的。p>
URL url = new URL(this.getUrl());
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches (false);
最佳答案
您需要使用HTTPURLConnection而不是URLConnection .
HTTPURLConnection 有 setRequestMethod
示例:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
注意:使用最新的 javadoc 而不是旧版本总是更好,1.4 是相当旧的 java 版本。
信用归Luigi R. Viggiano :
我上面的回答只是涉及如何访问setRequestMethod
。如果你不想使用setRequestMethod,而是实现POST,正如Luigi建议的,你可以忽略调用
setRequestMethod
并设置 setDoOutput(true)
。阅读此tutorial了解更多信息。
关于java - 如何将 URL 连接设置为 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14103983/