HttpURLConnection甚至在setDoOutput(true)之后执行get请求,setRequestMethod(“POST”)setRequestProperty(“Content”

时间:2012-09-27 20:10:42

标签: java android post http-post httpurlconnection

以下是代码:

String Surl = "http://mysite.com/somefile";
String charset = "UTF-8";
query = String.format("param1=%s&param2=%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(设备)。

我错过了什么?

1 个答案:

答案 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();