从Android 4.0开始,使用HttpURLConnection是http请求的首选方式 .

Problem

发送POST请求时,我们有效,请求在大约4分钟的空闲时间后发送两次 .

以下代码段重现了该问题:

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();
    }
  }
}

重现:按下按钮 . 等四分钟 . 再次按下按钮 . 第二个按钮命中的POST请求被发送到服务器两次 .

这个问题似乎只出现在Android 4.1及更高版本上 . 无法在4.0上重现它 .

Solution

解决了我们将系统属性 http.keepAlive 设置为 false 的问题 . 因此,POST请求仍然发送"Connection: keep-alive"头参数,但HttpURLConnection在4分钟空闲时间后不会尝试重新发送POST请求 .

Open Question

这是Android上url连接的预期行为吗?我认为永远不会重试POST请求 . 必须配置它(通过系统属性)非常容易出错 .