以下是代码:
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();
上述内容仍会执行GET
请求。我在服务器上使用PHP,并且能够访问查询&#39; name = value&#39;通过$_GET
变量而不是$_POST
变量加上参数
测试2.3.7(设备)。
我错过了什么?
答案 0 :(得分:3)
当您在网址中发送参数时,它们会被放入GET变量中。您应该在请求的POST主体中发布参数以实现您要查找的内容。您应该在connect()调用之前添加以下内容并删除“?” +来自网址的查询。
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();