當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpRetryException類代碼示例

本文整理匯總了Java中java.net.HttpRetryException的典型用法代碼示例。如果您正苦於以下問題:Java HttpRetryException類的具體用法?Java HttpRetryException怎麽用?Java HttpRetryException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


HttpRetryException類屬於java.net包,在下文中一共展示了HttpRetryException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testRewind

import java.net.HttpRetryException; //導入依賴的package包/類
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testRewind() throws Exception {
    // Post preserving redirect should fail.
    URL url = new URL(NativeTestServer.getRedirectToEchoBody());
    HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setFixedLengthStreamingMode(TestUtil.UPLOAD_DATA.length);
    try {
        OutputStream out = connection.getOutputStream();
        out.write(TestUtil.UPLOAD_DATA);
    } catch (HttpRetryException e) {
        assertEquals("Cannot retry streamed Http body", e.getMessage());
    }
    connection.disconnect();
}
 
開發者ID:lizhangqu,項目名稱:chromium-net-for-android,代碼行數:20,代碼來源:CronetFixedModeOutputStreamTest.java

示例2: sendResponseMessage

import java.net.HttpRetryException; //導入依賴的package包/類
@Override
void sendResponseMessage(HttpURLConnection connection) {
	InputStream response = null;
	byte[] responseBody = null;
	try {
		int statusCode = connection.getResponseCode();
		if(statusCode >= 300) {
			response = connection.getErrorStream();
			if(response != null) responseBody = Util.inputStreamToByteArray(response);
			sendFailMessage(new HttpRetryException(connection.getResponseMessage(), statusCode), 
					responseBody);		
		} else {
			response = connection.getInputStream();
			if(response != null) responseBody = Util.inputStreamToByteArray(response);
			sendSuccessMessage(statusCode, responseBody);
		}
	} catch(IOException e) {
		sendFailMessage(e, (byte[])null);
	} finally {
		if(response != null) Util.closeQuietly(response);
	}
}
 
開發者ID:leonardoxh,項目名稱:AsyncOkHttpClient,代碼行數:23,代碼來源:ByteAsyncHttpResponse.java

示例3: sendResponseMessage

import java.net.HttpRetryException; //導入依賴的package包/類
/**
    * Perform the connection with the given client
    * and return the response to the relative callback
    * @param connection the connection to execute and collect the informations
    */
void sendResponseMessage(HttpURLConnection connection) {
	String responseBody = null;
	InputStream response = null;
	try {
		int responseCode = connection.getResponseCode();
		if(responseCode >= 300) {
			response = connection.getErrorStream();
			if(response != null) responseBody = Util.inputStreamToString(response);
               sendFailMessage(new HttpRetryException(connection.getResponseMessage(),
                       responseCode), responseBody);
		} else {
			response = connection.getInputStream();
			if(response != null) responseBody = Util.inputStreamToString(response);
			sendSuccessMessage(responseCode, responseBody);
		}
	} catch(IOException e) {
		sendFailMessage(e, (String)null);
	} finally {
		if(response != null) Util.closeQuietly(response);
	}
}
 
開發者ID:leonardoxh,項目名稱:AsyncOkHttpClient,代碼行數:27,代碼來源:AsyncHttpResponse.java

示例4: testAuthenticateWithStreamingPost

import java.net.HttpRetryException; //導入依賴的package包/類
private void testAuthenticateWithStreamingPost(StreamingMode streamingMode) throws Exception {
  MockResponse pleaseAuthenticate = new MockResponse().setResponseCode(401)
      .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
      .setBody("Please authenticate.");
  server.enqueue(pleaseAuthenticate);

  Authenticator.setDefault(new RecordingAuthenticator());
  urlFactory.setClient(urlFactory.client().newBuilder()
      .authenticator(new JavaNetAuthenticator())
      .build());
  connection = urlFactory.open(server.url("/").url());
  connection.setDoOutput(true);
  byte[] requestBody = {'A', 'B', 'C', 'D'};
  if (streamingMode == StreamingMode.FIXED_LENGTH) {
    connection.setFixedLengthStreamingMode(requestBody.length);
  } else if (streamingMode == StreamingMode.CHUNKED) {
    connection.setChunkedStreamingMode(0);
  }
  OutputStream outputStream = connection.getOutputStream();
  outputStream.write(requestBody);
  outputStream.close();
  try {
    connection.getInputStream();
    fail();
  } catch (HttpRetryException expected) {
  }

  // no authorization header for the request...
  RecordedRequest request = server.takeRequest();
  assertNull(request.getHeader("Authorization"));
  assertEquals("ABCD", request.getBody().readUtf8());
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:33,代碼來源:URLConnectionTest.java

示例5: getResponse

import java.net.HttpRetryException; //導入依賴的package包/類
private HttpEngine getResponse() throws IOException {
    initHttpEngine();
    if (this.httpEngine.hasResponse()) {
        return this.httpEngine;
    }
    while (true) {
        if (execute(true)) {
            Response response = this.httpEngine.getResponse();
            Request followUp = this.httpEngine.followUpRequest();
            if (followUp == null) {
                this.httpEngine.releaseStreamAllocation();
                return this.httpEngine;
            }
            int i = this.followUpCount + 1;
            this.followUpCount = i;
            if (i > 20) {
                throw new ProtocolException("Too many follow-up requests: " + this
                        .followUpCount);
            }
            this.url = followUp.url();
            this.requestHeaders = followUp.headers().newBuilder();
            Sink requestBody = this.httpEngine.getRequestBody();
            if (!followUp.method().equals(this.method)) {
                requestBody = null;
            }
            if (requestBody == null || (requestBody instanceof RetryableSink)) {
                StreamAllocation streamAllocation = this.httpEngine.close();
                if (!this.httpEngine.sameConnection(followUp.httpUrl())) {
                    streamAllocation.release();
                    streamAllocation = null;
                }
                this.httpEngine = newHttpEngine(followUp.method(), streamAllocation,
                        (RetryableSink) requestBody, response);
            } else {
                throw new HttpRetryException("Cannot retry streamed HTTP body", this
                        .responseCode);
            }
        }
    }
}
 
開發者ID:JackChan1999,項目名稱:boohee_v5.6,代碼行數:41,代碼來源:HttpURLConnectionImpl.java

示例6: assertDeserialized

import java.net.HttpRetryException; //導入依賴的package包/類
public void assertDeserialized(Serializable reference, Serializable test) {

            HttpRetryException ref = (HttpRetryException) reference;
            HttpRetryException tst = (HttpRetryException) test;

            assertEquals("getLocation", ref.getLocation(), tst.getLocation());
            assertEquals("responseCode", ref.responseCode(), tst.responseCode());
            assertEquals("getReason", ref.getReason(), tst.getReason());
            assertEquals("getMessage", ref.getMessage(), tst.getMessage());
        }
 
開發者ID:keplersj,項目名稱:In-the-Box-Fork,代碼行數:11,代碼來源:HttpRetryExceptionTest.java

示例7: testAuthenticateWithStreamingPost

import java.net.HttpRetryException; //導入依賴的package包/類
private void testAuthenticateWithStreamingPost(StreamingMode streamingMode) throws Exception {
    MockResponse pleaseAuthenticate = new MockResponse()
            .setResponseCode(401)
            .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
            .setBody("Please authenticate.");
    server.enqueue(pleaseAuthenticate);
    server.play();

    Authenticator.setDefault(SIMPLE_AUTHENTICATOR);
    HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
    connection.setDoOutput(true);
    byte[] requestBody = { 'A', 'B', 'C', 'D' };
    if (streamingMode == StreamingMode.FIXED_LENGTH) {
        connection.setFixedLengthStreamingMode(requestBody.length);
    } else if (streamingMode == StreamingMode.CHUNKED) {
        connection.setChunkedStreamingMode(0);
    }
    OutputStream outputStream = connection.getOutputStream();
    outputStream.write(requestBody);
    outputStream.close();
    try {
        connection.getInputStream();
        fail();
    } catch (HttpRetryException expected) {
    }

    // no authorization header for the request...
    RecordedRequest request = server.takeRequest();
    assertContainsNoneMatching(request.getHeaders(), "Authorization: Basic .*");
    assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
}
 
開發者ID:keplersj,項目名稱:In-the-Box-Fork,代碼行數:32,代碼來源:URLConnectionTest.java

示例8: test_ConstructorLStringI

import java.net.HttpRetryException; //導入依賴的package包/類
public void test_ConstructorLStringI() {
    String [] message = {"Test message", "", "Message", "[email protected]#$% &*(", null};
    int [] codes = {400, 404, 200, 500, 0};

    for(int i = 0; i < message.length; i++) {
        HttpRetryException hre = new HttpRetryException(message[i],
                codes[i]);
        assertEquals(message[i], hre.getReason());
        assertTrue("responseCode is incorrect: " + hre.responseCode(),
                hre.responseCode() == codes[i]);
    }
}
 
開發者ID:keplersj,項目名稱:In-the-Box-Fork,代碼行數:13,代碼來源:OldHttpRetryExceptionTest.java

示例9: test_ConstructorLStringILString

import java.net.HttpRetryException; //導入依賴的package包/類
public void test_ConstructorLStringILString() {
    String [] message = {"Test message", "", "Message", "[email protected]#$% &*(", null};
    int [] codes = {400, -1, Integer.MAX_VALUE, Integer.MIN_VALUE, 0};
    String [] locations = {"file:\\error.txt", "http:\\localhost",
            "", null, ""};

    for(int i = 0; i < message.length; i++) {
        HttpRetryException hre = new HttpRetryException(message[i],
                codes[i], locations[i]);
        assertEquals(message[i], hre.getReason());
        assertTrue("responseCode is incorrect: " + hre.responseCode(),
                hre.responseCode() == codes[i]);
        assertEquals(locations[i], hre.getLocation());
    }
}
 
開發者ID:keplersj,項目名稱:In-the-Box-Fork,代碼行數:16,代碼來源:OldHttpRetryExceptionTest.java

示例10: testAuthenticateWithStreamingPost

import java.net.HttpRetryException; //導入依賴的package包/類
private void testAuthenticateWithStreamingPost(StreamingMode streamingMode) throws Exception {
  MockResponse pleaseAuthenticate = new MockResponse().setResponseCode(401)
      .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
      .setBody("Please authenticate.");
  server.enqueue(pleaseAuthenticate);
  server.play();

  Authenticator.setDefault(new RecordingAuthenticator());
  connection = client.open(server.getUrl("/"));
  connection.setDoOutput(true);
  byte[] requestBody = { 'A', 'B', 'C', 'D' };
  if (streamingMode == StreamingMode.FIXED_LENGTH) {
    connection.setFixedLengthStreamingMode(requestBody.length);
  } else if (streamingMode == StreamingMode.CHUNKED) {
    connection.setChunkedStreamingMode(0);
  }
  OutputStream outputStream = connection.getOutputStream();
  outputStream.write(requestBody);
  outputStream.close();
  try {
    connection.getInputStream();
    fail();
  } catch (HttpRetryException expected) {
  }

  // no authorization header for the request...
  RecordedRequest request = server.takeRequest();
  assertContainsNoneMatching(request.getHeaders(), "Authorization: Basic .*");
  assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
}
 
開發者ID:xin3liang,項目名稱:platform_external_okhttp,代碼行數:31,代碼來源:URLConnectionTest.java

示例11: testAuthenticateWithStreamingPost

import java.net.HttpRetryException; //導入依賴的package包/類
private void testAuthenticateWithStreamingPost(StreamingMode streamingMode) throws Exception {
  MockResponse pleaseAuthenticate = new MockResponse().setResponseCode(401)
      .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
      .setBody("Please authenticate.");
  server.enqueue(pleaseAuthenticate);
  server.play();

  Authenticator.setDefault(new RecordingAuthenticator());
  HttpURLConnection connection = client.open(server.getUrl("/"));
  connection.setDoOutput(true);
  byte[] requestBody = { 'A', 'B', 'C', 'D' };
  if (streamingMode == StreamingMode.FIXED_LENGTH) {
    connection.setFixedLengthStreamingMode(requestBody.length);
  } else if (streamingMode == StreamingMode.CHUNKED) {
    connection.setChunkedStreamingMode(0);
  }
  OutputStream outputStream = connection.getOutputStream();
  outputStream.write(requestBody);
  outputStream.close();
  try {
    connection.getInputStream();
    fail();
  } catch (HttpRetryException expected) {
  }

  // no authorization header for the request...
  RecordedRequest request = server.takeRequest();
  assertContainsNoneMatching(request.getHeaders(), "Authorization: Basic .*");
  assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
}
 
開發者ID:c-ong,項目名稱:mirrored-okhttp,代碼行數:31,代碼來源:URLConnectionTest.java

示例12: rewind

import java.net.HttpRetryException; //導入依賴的package包/類
@Override
public void rewind(UploadDataSink uploadDataSink) {
    uploadDataSink.onRewindError(
            new HttpRetryException("Cannot retry streamed Http body", -1));
}
 
開發者ID:lizhangqu,項目名稱:chromium-net-for-android,代碼行數:6,代碼來源:CronetFixedModeOutputStream.java

示例13: getResponse

import java.net.HttpRetryException; //導入依賴的package包/類
/**
 * Aggressively tries to get the final HTTP response, potentially making
 * many HTTP requests in the process in order to cope with redirects and
 * authentication.
 */
private HttpEngine getResponse() throws IOException {
  initHttpEngine();

  if (httpEngine.hasResponse()) {
    return httpEngine;
  }

  while (true) {
    if (!execute(true)) {
      continue;
    }

    Retry retry = processResponseHeaders();
    if (retry == Retry.NONE) {
      httpEngine.automaticallyReleaseConnectionToPool();
      return httpEngine;
    }

    // The first request was insufficient. Prepare for another...
    String retryMethod = method;
    OutputStream requestBody = httpEngine.getRequestBody();

    // Although RFC 2616 10.3.2 specifies that a HTTP_MOVED_PERM
    // redirect should keep the same method, Chrome, Firefox and the
    // RI all issue GETs when following any redirect.
    int responseCode = httpEngine.getResponseCode();
    if (responseCode == HTTP_MULT_CHOICE
        || responseCode == HTTP_MOVED_PERM
        || responseCode == HTTP_MOVED_TEMP
        || responseCode == HTTP_SEE_OTHER) {
      retryMethod = "GET";
      requestBody = null;
    }

    if (requestBody != null && !(requestBody instanceof RetryableOutputStream)) {
      throw new HttpRetryException("Cannot retry streamed HTTP body", responseCode);
    }

    if (retry == Retry.DIFFERENT_CONNECTION) {
      httpEngine.automaticallyReleaseConnectionToPool();
    }

    httpEngine.release(false);

    httpEngine = newHttpEngine(retryMethod, rawRequestHeaders, httpEngine.getConnection(),
        (RetryableOutputStream) requestBody);

    if (requestBody == null) {
      // Drop the Content-Length header when redirected from POST to GET.
      httpEngine.getRequestHeaders().removeContentLength();
    }
  }
}
 
開發者ID:aabognah,項目名稱:LoRaWAN-Smart-Parking,代碼行數:59,代碼來源:HttpURLConnectionImpl.java

示例14: getResponse

import java.net.HttpRetryException; //導入依賴的package包/類
/**
 * Aggressively tries to get the final HTTP response, potentially making many HTTP requests in the
 * process in order to cope with redirects and authentication.
 */
private HttpEngine getResponse() throws IOException {
  initHttpEngine();

  if (httpEngine.hasResponse()) {
    return httpEngine;
  }

  while (true) {
    if (!execute(true)) {
      continue;
    }

    Response response = httpEngine.getResponse();
    Request followUp = httpEngine.followUpRequest();

    if (followUp == null) {
      httpEngine.releaseStreamAllocation();
      return httpEngine;
    }

    if (++followUpCount > HttpEngine.MAX_FOLLOW_UPS) {
      throw new ProtocolException("Too many follow-up requests: " + followUpCount);
    }

    // The first request was insufficient. Prepare for another...
    url = followUp.url().url();
    requestHeaders = followUp.headers().newBuilder();

    // Although RFC 2616 10.3.2 specifies that a HTTP_MOVED_PERM redirect
    // should keep the same method, Chrome, Firefox and the RI all issue GETs
    // when following any redirect.
    Sink requestBody = httpEngine.getRequestBody();
    if (!followUp.method().equals(method)) {
      requestBody = null;
    }

    if (requestBody != null && !(requestBody instanceof RetryableSink)) {
      throw new HttpRetryException("Cannot retry streamed HTTP body", responseCode);
    }

    StreamAllocation streamAllocation = httpEngine.close();
    if (!httpEngine.sameConnection(followUp.url())) {
      streamAllocation.release();
      streamAllocation = null;
    }

    httpEngine = newHttpEngine(followUp.method(), streamAllocation, (RetryableSink) requestBody,
        response);
  }
}
 
開發者ID:lizhangqu,項目名稱:PriorityOkHttp,代碼行數:55,代碼來源:HttpURLConnectionImpl.java

示例15: checkErrorsAndUpdateStatus

import java.net.HttpRetryException; //導入依賴的package包/類
/**
 *  Checks for errors from standard read/write requests and performs
 *  occasional status checks.
 *
 *  @param line the response from the server to analyze
 *  @param caller what we tried to do
 *  @throws CredentialNotFoundException if permission denied
 *  @throws AccountLockedException if the user is blocked
 *  @throws HttpRetryException if the database is locked or action was
 *  throttled and a retry failed
 *  @throws AssertionError if assertions fail
 *  @throws UnknownError in the case of a MediaWiki bug
 *  @since 0.18
 */
protected void checkErrorsAndUpdateStatus(String line, String caller) throws IOException, LoginException
{
    // perform various status checks every 100 or so edits
    if (statuscounter > statusinterval)
    {
        // purge user rights in case of desysop or loss of other priviliges
        user.getUserInfo();
        if ((assertion & ASSERT_SYSOP) == ASSERT_SYSOP && !user.isA("sysop"))
            // assert user.isA("sysop") : "Sysop privileges missing or revoked, or session expired";
            throw new AssertionError("Sysop privileges missing or revoked, or session expired");
        // check for new messages
        if ((assertion & ASSERT_NO_MESSAGES) == ASSERT_NO_MESSAGES && hasNewMessages())
            // assert !hasNewMessages() : "User has new messages";
            throw new AssertionError("User has new messages");
        statuscounter = 0;
    }
    else
        statuscounter++;

    // successful
    if (line.contains("result=\"Success\""))
        return;
    // empty response from server
    if (line.isEmpty())
        throw new UnknownError("Received empty response from server!");
    // assertions
    if ((assertion & ASSERT_BOT) == ASSERT_BOT && line.contains("error code=\"assertbotfailed\""))
        // assert !line.contains("error code=\"assertbotfailed\"") : "Bot privileges missing or revoked, or session expired.";
        throw new AssertionError("Bot privileges missing or revoked, or session expired.");
    if ((assertion & ASSERT_USER) == ASSERT_USER && line.contains("error code=\"assertuserfailed\""))
        // assert !line.contains("error code=\"assertuserfailed\"") : "Session expired.";
        throw new AssertionError("Session expired.");
    if (line.contains("error code=\"permissiondenied\""))
        throw new CredentialNotFoundException("Permission denied."); // session expired or stupidity
    // rate limit (automatic retry), though might be a long one (e.g. email)
    if (line.contains("error code=\"ratelimited\""))
    {
        log(Level.WARNING, caller, "Server-side throttle hit.");
        throw new HttpRetryException("Action throttled.", 503);
    }
    // blocked! (note here the \" in blocked is deliberately missing for emailUser()
    if (line.contains("error code=\"blocked") || line.contains("error code=\"autoblocked\""))
    {
        log(Level.SEVERE, caller, "Cannot " + caller + " - user is blocked!.");
        throw new AccountLockedException("Current user is blocked!");
    }
    // database lock (automatic retry)
    if (line.contains("error code=\"readonly\""))
    {
        log(Level.WARNING, caller, "Database locked!");
        throw new HttpRetryException("Database locked!", 503);
    }
    // unknown error
    if (line.contains("error code=\"unknownerror\""))
        throw new UnknownError("Unknown MediaWiki API error, response was " + line);
    // generic (automatic retry)
    throw new IOException("MediaWiki error, response was " + line);
}
 
開發者ID:DiscourseDB,項目名稱:discoursedb-core,代碼行數:73,代碼來源:Wiki.java


注:本文中的java.net.HttpRetryException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。