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.

3
  • If you're using HTTPS, you should use HttpsURLConnection: developer.android.com/reference/javax/net/ssl/… Commented Feb 8, 2016 at 22:06
  • There are multiple connections made throughout the app, some http some https, hence why this bug was a bit of a mess to chase down. Commented Feb 8, 2016 at 22:15
  • 1
    Ahh, I see. Glad you got it sorted! Commented Feb 8, 2016 at 22:18

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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
}

}

2 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.