1

I need HttpUrlConnection to use POST method but it's not playing nice.

connection = (HttpURLConnection) link.openConnection();
connection.setRequestMethod("POST");
...

In the debugger:

  • on the first line I see connection = null as expected
  • second line I can see connection.method = "GET" as expected
  • further on I see connection.method = "GET" which is not expected

How can I get HttpUrlConnection to use POST ?

Solution

If you open a HttpUrlconnection on the "HTTPS" protocol, the connection permanently overrides the connection to "GET".

Via "HTTP" the connection will allow "POST" method if it is manually set.

Community
  • 1
  • 1
Jacksonkr
  • 31,583
  • 39
  • 180
  • 284

3 Answers3

1

Try it:

public static String executePostHttpRequest(final String path, Map<String, String> params) throws ClientProtocolException, IOException {
    String result = null;
    HttpURLConnection urlConnection = null;
    try {
        String postData = getQuery(params);
        byte[] postDataBytes = postData.getBytes("UTF-8");

        URL url = new URL(path);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(30000);
        urlConnection.setReadTimeout(30000);
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
        urlConnection.setRequestProperty("charset", "UTF-8");
        urlConnection.setRequestProperty("Content-Length", Integer.toString(postDataBytes.length));

        OutputStream out = urlConnection.getOutputStream();
        out.write(postDataBytes);
        out.close();
        result = readStream(urlConnection.getInputStream());
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    return result;
}

Where:

private static String getQuery(Map<String, String> params) throws UnsupportedEncodingException{
    StringBuilder result = new StringBuilder(); 
    boolean haveData = params != null && params.size() > 0;
    if (haveData) {
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()){
            String value = entry.getValue();
            if (value != null) {
                if (first) {
                     first = false;
                } else {
                     result.append("&");
                }
                result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                result.append("=");
                result.append(URLEncoder.encode(value, "UTF-8"));
            }
        }
    }
    return result.toString();
}

P.S. I didn't move hard-coded strings to constants for better understanding.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
Mk.Sl.
  • 2,879
  • 1
  • 11
  • 11
1

Solution

If you open a HttpUrlconnection on the "HTTPS" protocol, the connection permanently overrides the connection to "GET".

Via "HTTP" the connection will allow "POST" method if it is manually set.

Community
  • 1
  • 1
Jacksonkr
  • 31,583
  • 39
  • 180
  • 284
0
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

}

Nidhin Prathap
  • 696
  • 5
  • 15
  • `HttpClient` is what used to be in this app but everything has been moved over due to a TLS 1.2 complication, hence why I'm working with `HttpUrlConnection` – Jacksonkr Feb 08 '16 at 19:39
  • 1
    https://www.numetriclabz.com/android-post-and-get-request-using-httpurlconnection/ – Nidhin Prathap Feb 08 '16 at 19:43