Thursday, April 4, 2013

HttpURLConnection sends POST request twice


Using HttpURLConnection is the prefered way for http requests since Android 4.0.


Problem


When sending POST requests we had the effect, that the request was sent twice after an idle period of around 4 minutes.


The following snippet reproduces the problem:



public class MainActivity extends Activity {

@Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
Button button = new Button( this );
button.setText( "Perform POST request" );
button.setOnClickListener( new OnClickListener() {

@Override
public void onClick( View v ) {

new Thread( new Runnable() {

@Override
public void run() {
makePostRequest();
}

} ).start();
}
} );
setContentView( button );
}

private void makePostRequest() {
try {
String target = "http://server.com/path";
System.out.println( "Sending POST request: " + target );
URL url = new URL( target );
HttpURLConnection conn = ( HttpURLConnection )url.openConnection();
conn.setDoOutput( true );
System.out.println( "Response: " + conn.getResponseCode() );
} catch( Exception e ) {
e.printStackTrace();
}
}
}

To reproduce: Hit the button. Wait four minutes. Hit the button again. The POST request of the second button hit is send to the server twice.


The issue only seems to arise on Android 4.1 and upwards. Couldn't reproduce it on 4.0.


Solution


The solve the issue we set the system property http.keepAlive to false. Thereby the POST request still sends the "Connection: keep-alive" header parameter but the HttpURLConnection does not attempt to resend a POST request after the 4 minutes idle period.


Open Question


Is that the expected behavior of the url connection on android? I would assume that POST requests are never retried. Having to configure it (via a system property) is very error prone.



.

forum.xda-developers.com

No comments:

Post a Comment

Google Voice on T-Mobile? [General]

Google Voice on T-Mobile? So I recently switched from a GNex on Verizon to a Moto X DE on T-Mobile. I had always used Google Voice for my v...