Using HttpURLConnection is the preferred way for HTTP requests with Android 4.0.
Problem
When sending POST requests, we had the effect that the request was sent twice after a downtime of about 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 ();
}
}
}
Play: press the button. Wait four minutes. Press the button again. The POST request of the second button press is sent to the server twice.
The problem only occurs on Android 4.1 and higher. Could not play it on 4.0.
Decision
To solve the problem, we set the system property http.keepAlive to false . Thus, the POST request still sends the "Connection: keep-alive" header parameter, but the HttpURLConnection does not attempt to send the POST request after a 4-minute wait period.
Open question
Is the expected url connection behavior on Android? I would suggest that POST requests never repeat. The need to configure it (through the system property) is very error prone.
source share