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


Java HttpRequest.setUnsuccessfulResponseHandler方法代碼示例

本文整理匯總了Java中com.google.api.client.http.HttpRequest.setUnsuccessfulResponseHandler方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpRequest.setUnsuccessfulResponseHandler方法的具體用法?Java HttpRequest.setUnsuccessfulResponseHandler怎麽用?Java HttpRequest.setUnsuccessfulResponseHandler使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.google.api.client.http.HttpRequest的用法示例。


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

示例1: initialize

import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
@Override
public void initialize(HttpRequest request) throws IOException {
    if (connectTimeout != null) {
        request.setConnectTimeout((int) connectTimeout.millis());
    }
    if (readTimeout != null) {
        request.setReadTimeout((int) readTimeout.millis());
    }

    request.setIOExceptionHandler(ioHandler);
    request.setInterceptor(credential);

    request.setUnsuccessfulResponseHandler((req, resp, supportsRetry) -> {
                // Let the credential handle the response. If it failed, we rely on our backoff handler
                return credential.handleResponse(req, resp, supportsRetry) || handler.handleResponse(req, resp, supportsRetry);
            }
    );
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:19,代碼來源:GoogleCloudStorageService.java

示例2: initialize

import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
@Override
public void initialize(HttpRequest request) throws IOException {
  // Set a timeout for hanging-gets.
  // TODO: Do this exclusively for work requests.
  request.setReadTimeout(HANGING_GET_TIMEOUT_SEC * 1000);

  LoggingHttpBackOffHandler loggingHttpBackOffHandler = new LoggingHttpBackOffHandler(
      sleeper,
      // Back off on retryable http errors and IOExceptions.
      // A back-off multiplier of 2 raises the maximum request retrying time
      // to approximately 5 minutes (keeping other back-off parameters to
      // their default values).
      new ExponentialBackOff.Builder().setNanoClock(nanoClock).setMultiplier(2).build(),
      new ExponentialBackOff.Builder().setNanoClock(nanoClock).setMultiplier(2).build(),
      ignoredResponseCodes
  );

  request.setUnsuccessfulResponseHandler(loggingHttpBackOffHandler);
  request.setIOExceptionHandler(loggingHttpBackOffHandler);

  // Set response initializer
  if (responseInterceptor != null) {
    request.setResponseInterceptor(responseInterceptor);
  }
}
 
開發者ID:apache,項目名稱:beam,代碼行數:26,代碼來源:RetryHttpRequestInitializer.java

示例3: execute

import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
private <U, T extends ResponseEnvelope<U>> U execute(final HttpRequest httpRequest, final Class<T> responseType) throws IOException {
   httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()));
   if (authToken != null) {
      HttpHeaders headers = httpRequest.getHeaders();
      headers.set("X-Auth-Token", authToken);
   }

   HttpResponse httpResponse = httpRequest.execute();
   T response = httpResponse.parseAs(responseType);

   // Update authToken, if necessary
   if (response.getAuthToken() != null) {
      authToken = response.getAuthToken();
   }

   return response.getData();
}
 
開發者ID:scratch-wireless,項目名稱:kazoo-client,代碼行數:18,代碼來源:KazooConnection.java

示例4: initialize

import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
/**
 * Initializes this {@link com.google.api.client.auth.oauth2.Credential} subclass. Adds an
 * additional interceptor that properly sets the default encoding of the "application/json"
 * media type to UTF-8 as required by <a href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a>.
 * 
 * @param request The {@link HttpRequest} to be initialized.
 */
@Override
public void initialize(HttpRequest request) throws IOException {
	// Initially, pass the initialization on to super.
	super.initialize(request);
	
	// Set the timeouts.
	request.setConnectTimeout(3 * 600000);  // 10 minutes connect timeout
	request.setReadTimeout(3 * 600000);  // 10 minutes read timeout
	
	// Add an additional interceptor.
	request.setResponseInterceptor(new HttpResponseInterceptor() {
		@Override
		public void interceptResponse(HttpResponse response) throws IOException {
			// Decode JSON as UTF-8 if no charset is specified.
			if (response.getContentType().equals("application/json") &&
				response.getMediaType() != null &&
				response.getMediaType().getCharsetParameter() == null)
			{
				response.getMediaType().setCharsetParameter(StandardCharsets.UTF_8);
			}
		}
	});
	
	// Add a custom handler for unsuccessful responses.
	request.setUnsuccessfulResponseHandler(
			new UnsuccessfulResponseHandler());
}
 
開發者ID:ambi-verse,項目名稱:nlu-api-client-java,代碼行數:35,代碼來源:Credential.java

示例5: initialize

import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
@Override
public void initialize(HttpRequest request) throws IOException {
	request.setInterceptor(credential);

	// Exponential Back-off for 5xx response and 403 rate limit exceeded
	// error
	HttpBackOffUnsuccessfulResponseHandler backOffHandler = getHttpBackOffUnsuccessfulResponseHandler();

	request.setUnsuccessfulResponseHandler(
			new CompositeHttpUnsuccessfulResponseHandler(credential, backOffHandler));

	// Back-off for socket connection error
	request.setIOExceptionHandler(getHttpBackOffIOExceptionHandler());
}
 
開發者ID:cchabanois,項目名稱:mesfavoris,代碼行數:15,代碼來源:GDriveBackOffHttpRequestInitializer.java

示例6: initialize

import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
@Override
public void initialize(HttpRequest httpRequest) {
    final HttpUnsuccessfulResponseHandler backoffHandler =
            new HttpBackOffUnsuccessfulResponseHandler(
                    new ExponentialBackOff.Builder()
                            .setMaxElapsedTimeMillis(((int) maxWait.getMillis()))
                            .build())
                    .setSleeper(sleeper);

    httpRequest.setInterceptor(wrappedCredential);
    httpRequest.setUnsuccessfulResponseHandler(
            new HttpUnsuccessfulResponseHandler() {
                int retry = 0;

                @Override
                public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) throws IOException {
                    if (wrappedCredential.handleResponse(
                            request, response, supportsRetry)) {
                        // If credential decides it can handle it,
                        // the return code or message indicated
                        // something specific to authentication,
                        // and no backoff is desired.
                        return true;
                    } else if (backoffHandler.handleResponse(
                            request, response, supportsRetry)) {
                        // Otherwise, we defer to the judgement of
                        // our internal backoff handler.
                        logger.debug("Retrying [{}] times : [{}]", retry, request.getUrl());
                        return true;
                    } else {
                        return false;
                    }
                }
            });
    httpRequest.setIOExceptionHandler(
            new HttpBackOffIOExceptionHandler(
                    new ExponentialBackOff.Builder()
                            .setMaxElapsedTimeMillis(((int) maxWait.getMillis()))
                            .build())
                    .setSleeper(sleeper)
    );
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:43,代碼來源:RetryHttpInitializerWrapper.java

示例7: initialize

import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
@Override
public void initialize(HttpRequest httpRequest) throws IOException {
  httpRequest.setUnsuccessfulResponseHandler(new NullCredentialHttpUnsuccessfulResponseHandler());
}
 
開發者ID:apache,項目名稱:beam,代碼行數:5,代碼來源:NullCredentialInitializer.java

示例8: initialize

import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
public void initialize(HttpRequest request) throws IOException {
	request.setInterceptor(this);
	request.setUnsuccessfulResponseHandler(new HBSPTUnsuccessfulResponseHandler(jsonFactory));
}
 
開發者ID:ShangriLaFarm,項目名稱:hubspot-api-java-client,代碼行數:5,代碼來源:HBSPTHttpRequestInitializer.java

示例9: getConfig

import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
/** Publish an event or state message using Cloud IoT Core via the HTTP API. */
public static void getConfig(String urlPath, String token, String projectId,
    String cloudRegion, String registryId, String deviceId, String version)
    throws UnsupportedEncodingException, IOException, JSONException, ProtocolException {
  // Build the resource path of the device that is going to be authenticated.
  String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryId, deviceId);
  urlPath = urlPath + devicePath + "/config?local_version=" + version;

  HttpRequestFactory requestFactory =
      HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest request) {
          request.setParser(new JsonObjectParser(JSON_FACTORY));
        }
      });

  final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
  HttpHeaders heads = new HttpHeaders();

  heads.setAuthorization(String.format("Bearer %s", token));
  heads.setContentType("application/json; charset=UTF-8");
  heads.setCacheControl("no-cache");

  req.setHeaders(heads);
  ExponentialBackOff backoff = new ExponentialBackOff.Builder()
      .setInitialIntervalMillis(500)
      .setMaxElapsedTimeMillis(900000)
      .setMaxIntervalMillis(6000)
      .setMultiplier(1.5)
      .setRandomizationFactor(0.5)
      .build();
  req.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
  HttpResponse res = req.execute();
  System.out.println(res.getStatusCode());
  System.out.println(res.getStatusMessage());
  InputStream in = res.getContent();

  System.out.println(CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8)));
}
 
開發者ID:GoogleCloudPlatform,項目名稱:java-docs-samples,代碼行數:43,代碼來源:HttpExample.java

示例10: publishMessage

import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
/** Publish an event or state message using Cloud IoT Core via the HTTP API. */
public static void publishMessage(String payload, String urlPath, String messageType,
    String token, String projectId, String cloudRegion, String registryId, String deviceId)
    throws UnsupportedEncodingException, IOException, JSONException, ProtocolException {
  // Build the resource path of the device that is going to be authenticated.
  String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryId, deviceId);
  String urlSuffix = messageType.equals("event") ? "publishEvent" : "setState";

  // Data sent through the wire has to be base64 encoded.
  Base64.Encoder encoder = Base64.getEncoder();

  String encPayload = encoder.encodeToString(payload.getBytes("UTF-8"));

  urlPath = urlPath + devicePath + ":" + urlSuffix;


  final HttpRequestFactory requestFactory =
      HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest request) {
          request.setParser(new JsonObjectParser(JSON_FACTORY));
        }
      });

  HttpHeaders heads = new HttpHeaders();
  heads.setAuthorization(String.format("Bearer %s", token));
  heads.setContentType("application/json; charset=UTF-8");
  heads.setCacheControl("no-cache");

  // Add post data. The data sent depends on whether we're updating state or publishing events.
  JSONObject data = new JSONObject();
  if (messageType.equals("event")) {
    data.put("binary_data", encPayload);
  } else {
    JSONObject state = new JSONObject();
    state.put("binary_data", encPayload);
    data.put("state", state);
  }

  ByteArrayContent content = new ByteArrayContent(
      "application/json", data.toString().getBytes("UTF-8"));

  final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
  req.setHeaders(heads);
  req.setContent(content);
  req.setRequestMethod("POST");
  ExponentialBackOff backoff = new ExponentialBackOff.Builder()
      .setInitialIntervalMillis(500)
      .setMaxElapsedTimeMillis(900000)
      .setMaxIntervalMillis(6000)
      .setMultiplier(1.5)
      .setRandomizationFactor(0.5)
      .build();
  req.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));

  HttpResponse res = req.execute();
  System.out.println(res.getStatusCode());
  System.out.println(res.getStatusMessage());
}
 
開發者ID:GoogleCloudPlatform,項目名稱:java-docs-samples,代碼行數:63,代碼來源:HttpExample.java


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