[英]HttpURLConnection doing a get request even after setDoOutput(true), setRequestMethod(“POST”) setRequestProperty("Content
Here is the code: 这是代码:
String Surl = "http://mysite.com/somefile";
String charset = "UTF-8";
query = String.format("param1=%s¶m2=%s",
URLEncoder.encode("param1", charset),
URLEncoder.encode("param2", charset));
HttpURLConnection urlConnection = (HttpURLConnection) new URL(Surl + "?" + query).openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Accept-Charset", charset);
urlConnection.setRequestProperty("User-Agent","<em>Android</em>");
urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=" + charset);
urlConnection.connect();
The above still does a GET
request. 以上仍然是GET
请求。 I am using PHP on the server and am able to access the query's 'name=value' params through the $_GET
variable and not the $_POST
variable 我在服务器上使用PHP,并且能够通过$_GET
变量而不是$_POST
变量访问查询的'name = value'参数
Tested on 2.3.7(device). 测试2.3.7(设备)。
What am I missing ? 我错过了什么?
When you send parameters in the url they are put in the GET variable. 当您在URL中发送参数时,它们将被放入GET变量中。 You should be posting the parameters in the POST body of the request to achieve what you are looking for. 您应该在请求的POST主体中发布参数以实现您要查找的内容。 You should add the following just before the connect() call and remove the "?" 您应该在connect()调用之前添加以下内容并删除“?” + query from the url. +来自网址的查询。
urlConnection.setRequestProperty("Content-Length", String.valueOf(query.getBytes().length));
urlConnection.setFixedLengthStreamingMode(query.getBytes().length);
OutputStream output = new BufferedOutputStream(urlConnection.getOutputStream());
output.write(query.getBytes());
output.flush();
output.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.