Ejemplo n.º 1
0
  /**
   * 运行时,添加JVM参数“-Dsun.net.http.retryPost=false”,可阻止自动重连。
   *
   * @see 'http://www.coderanch.com/t/490463/sockets/java/Timeout-retry-URLHTTPRequest'
   */
  @Test
  public void testConnectionResetByHttpURLConnection() throws IOException {
    testConnectionResetCount = 0;

    String resp = null;
    try {
      HttpURLConnection conn =
          (HttpURLConnection) new URL("http://localhost:65532/soso").openConnection();
      conn.setDoOutput(true);
      conn.setRequestMethod("POST");
      conn.getOutputStream().write("username".getBytes());
      resp = conn.getResponseCode() + "";
    } catch (IOException e) {
      Throwable ee = ExceptionUtils.getRootCause(e);
      if (ee == null) {
        ee = e;
      }
      Logger.error(this, "", ee);
      Assert.assertNotSame(NoHttpResponseException.class, ee.getClass());
      Assert.assertSame(SocketException.class, ee.getClass());
      Assert.assertTrue(
          "Connection reset".equals(ee.getMessage())
              || "Socket closed".equals(ee.getMessage())
              || "Unexpected end of file from server".equals(ee.getMessage()));
    } finally {
      Logger.info(
          this,
          "resp[HttpURLConnection]-["
              + testConnectionResetCount
              + "]=========["
              + resp
              + "]=========");
    }
    Assert.assertEquals(2, testConnectionResetCount);
  }
Ejemplo n.º 2
0
    @Override
    public HTTPResponse call() throws Exception {
      final HttpURLConnection hc = (HttpURLConnection) uri.toURL().openConnection();
      hc.setReadTimeout(SOCKET_TIMEOUT);
      try {
        while (!stop) {
          try {
            final int code = hc.getResponseCode();

            final InputStream input = hc.getInputStream();
            final ByteList bl = new ByteList();
            for (int i; (i = input.read()) != -1; ) bl.add(i);

            return new HTTPResponse(code, bl.toString());
          } catch (final SocketTimeoutException e) {
          }
        }
        return null;
      } finally {
        hc.disconnect();
      }
    }
Ejemplo n.º 3
0
    @Override
    public HTTPResponse call() throws Exception {
      final HttpURLConnection hc = (HttpURLConnection) uri.toURL().openConnection();
      try {
        hc.setDoOutput(true);
        hc.setRequestMethod(method.name());
        hc.setRequestProperty(MimeTypes.CONTENT_TYPE, MimeTypes.APP_XML);
        hc.getOutputStream().write(content);
        hc.getOutputStream().close();

        hc.setReadTimeout(SOCKET_TIMEOUT);
        while (!stop) {
          try {
            return new HTTPResponse(hc.getResponseCode());
          } catch (final SocketTimeoutException e) {
          }
        }
        return null;
      } finally {
        hc.disconnect();
      }
    }