简体   繁体   中英

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&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();

The above still does a GET request. 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
Tested on 2.3.7(device).

What am I missing ?

When you send parameters in the url they are put in the GET variable. You should be posting the parameters in the POST body of the request to achieve what you are looking for. You should add the following just before the connect() call and remove the "?" + 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM