HttpURLConnection 即使在 setDoOutput(true), setRequestMethod("POST") setRequestProperty("Content 之后也执行



这是代码:

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,并且能够通过 $_GET 变量而不是 $_POST 变量
访问查询的"名称=值"参数在 2.3.7(设备上)上测试。

我错过了什么?

当您在 url 中发送参数时,它们被放入 GET 变量中。您应该在请求的 POST 正文中发布参数以实现您正在寻找的内容。您应该在 connect() 调用之前添加以下内容,并从 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();

最新更新