Android 4.0 ICS turning HttpURLConnection GET requests into POST requests

南楼画角 提交于 2019-11-27 14:25:51

This behaviour is described in Android Developers: HttpURLConnection

HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has been called.

What's strange though is that this has not actually been the behaviour until 4.0, so I would imagine it's going to break many existing published apps.

There is more on this at Android 4.0 turns GET into POST.

Removing this line worked for me:

connection.setDoOutput(true);

4.0 thinks with this line it should definitely be POST.

Get rid of this:

connection.setRequestProperty("Content-Type","application/x-www-form-urlendcoded");

This tells the API this is a POST.

UPDATE on how it could be done via HttpClient:

String response = null;
HttpClient httpclient = null;
try {
    HttpGet httpget = new HttpGet(yourUrl);
    httpget.setHeader("Authorization", "GoogleLogin auth=" + auth);
    httpclient = new DefaultHttpClient();
    HttpResponse httpResponse = httpclient.execute(httpget);

    final int statusCode = httpResponse.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
        throw new Exception("Got HTTP " + statusCode 
            + " (" + httpResponse.getStatusLine().getReasonPhrase() + ')');
    }

    response = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);

} catch (Exception e) {
    e.printStackTrace();
    // do some error processing here
} finally {
    if (httpclient != null) {
        httpclient.getConnectionManager().shutdown();
    }
}

This is one that got me - basically by setting setDoOutput(true) it forces a POST request when you make the connection, even if you specify this is a GET in the setRequestMethod:

HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has been called. Other HTTP methods (OPTIONS, HEAD, PUT, DELETE and TRACE) can be used with setRequestMethod(String).

This caught me a while back - very frustrating ...

See http://developer.android.com/reference/java/net/HttpURLConnection.html and go to HTTP Methods heading

I've found that pre-ICS one could get away with making a body-less POST without providing a Content-Length value, however post-ICS you must set Content-Length: 0.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!