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


Java HttpRequest類代碼示例

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


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

示例1: deleteInstanceId

import com.google.api.client.http.HttpRequest; //導入依賴的package包/類
private Task<Void> deleteInstanceId(final String instanceId) {
  checkArgument(!Strings.isNullOrEmpty(instanceId), "instance ID must not be null or empty");
  return ImplFirebaseTrampolines.submitCallable(app, new Callable<Void>(){
    @Override
    public Void call() throws Exception {
      String url = String.format(
          "%s/project/%s/instanceId/%s", IID_SERVICE_URL, projectId, instanceId);
      HttpRequest request = requestFactory.buildDeleteRequest(new GenericUrl(url));
      request.setParser(new JsonObjectParser(jsonFactory));
      request.setResponseInterceptor(interceptor);
      HttpResponse response = null;
      try {
        response = request.execute();
        ByteStreams.exhaust(response.getContent());
      } catch (Exception e) {
        handleError(instanceId, e);
      } finally {
        if (response != null) {
          response.disconnect();
        }
      }
      return null;
    }
  });
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:26,代碼來源:FirebaseInstanceId.java

示例2: signInWithCustomToken

import com.google.api.client.http.HttpRequest; //導入依賴的package包/類
private String signInWithCustomToken(String customToken) throws IOException {
  GenericUrl url = new GenericUrl(ID_TOOLKIT_URL + "?key="
      + IntegrationTestUtils.getApiKey());
  Map<String, Object> content = ImmutableMap.<String, Object>of(
      "token", customToken, "returnSecureToken", true);
  HttpRequest request = transport.createRequestFactory().buildPostRequest(url,
      new JsonHttpContent(jsonFactory, content));
  request.setParser(new JsonObjectParser(jsonFactory));
  HttpResponse response = request.execute();
  try {
    GenericJson json = response.parseAs(GenericJson.class);
    return json.get("idToken").toString();
  } finally {
    response.disconnect();
  }
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:17,代碼來源:FirebaseAuthIT.java

示例3: createThumbnail

import com.google.api.client.http.HttpRequest; //導入依賴的package包/類
/**
 * Richiede ad Alfresco la creazione di una <i>thumbnail</i>.
 * <p>
 * Si tenga presente che in caso di creazione asincrona la <i>thumbnail</i> potrebbe non essere
 * subito disponibile anche se il metodo ha restituito informazioni valide.
 * 
 * @param pContentId
 *            L'id del contenuto.
 * @param pThumbDefinition
 *            Il nome della <i>thumbnail</i> di cui si richiede la crezione.
 * @param pAsync
 *            Se la crazione deve essere sincrona ({@code true} o asincrona ({@false}).
 * 
 * @return La <i>thumbnail</i> richiesta o {@code null} se il tipo di <i>thumbnail</i> di cui si
 *         è richiesta la creazione non è valido per il contenuto specificato.
 * 
 * @throws IOException
 */
public Thumbnail createThumbnail(String pContentId, String pThumbDefinition, boolean pAsync) throws IOException {
	/*
	 * POST <base>/content{property}/thumbnails?as={async?}
	 * 
	 * {
	 *     "thumbnailName": <name>
	 * }
	 */
	GenericUrl lUrl = getContentUrl(pContentId);
	lUrl.appendRawPath(URL_RELATIVE_THUMBNAILS);
	lUrl.set("as", pAsync);

	// Recupero delle definizioni valide
	// Purtroppo Alfresco restituisce successo anche se viene richiesta la generazione di una
	// thumbnail non possibile. Controllando preventivamente si può restituire null.
	List<String> lThumbDefinitions = getThumbnailDefinitions(pContentId);
	if (!lThumbDefinitions.contains(pThumbDefinition)) {
		return null;
	}

	JsonHttpContent lContent = new JsonHttpContent(JSON_FACTORY, new Thumbnail(pThumbDefinition));

	HttpHeaders lRequestHeaders = new HttpHeaders().setContentType("application/json");
	HttpRequest lRequest =
	        mHttpRequestFactory.buildPostRequest(lUrl, lContent).setHeaders(lRequestHeaders);

	HttpResponse lResponse = lRequest.execute();
	Thumbnail lThumbnail = lResponse.parseAs(Thumbnail.class);

	return lThumbnail;
}
 
開發者ID:MakeITBologna,項目名稱:zefiro,代碼行數:50,代碼來源:NodeService.java

示例4: 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

示例5: testSimpleRetry

import com.google.api.client.http.HttpRequest; //導入依賴的package包/類
public void testSimpleRetry() throws Exception {
    FailThenSuccessBackoffTransport fakeTransport =
            new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 3);

    MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder()
            .build();
    MockSleeper mockSleeper = new MockSleeper();

    RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper,
        TimeValue.timeValueSeconds(5));

    Compute client = new Compute.Builder(fakeTransport, new JacksonFactory(), null)
            .setHttpRequestInitializer(retryHttpInitializerWrapper)
            .setApplicationName("test")
            .build();

    HttpRequest request = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
    HttpResponse response = request.execute();

    assertThat(mockSleeper.getCount(), equalTo(3));
    assertThat(response.getStatusCode(), equalTo(200));
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:23,代碼來源:RetryHttpInitializerWrapperTests.java

示例6: testIOExceptionRetry

import com.google.api.client.http.HttpRequest; //導入依賴的package包/類
public void testIOExceptionRetry() throws Exception {
    FailThenSuccessBackoffTransport fakeTransport =
            new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 1, true);

    MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder()
            .build();
    MockSleeper mockSleeper = new MockSleeper();
    RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper,
        TimeValue.timeValueMillis(500));

    Compute client = new Compute.Builder(fakeTransport, new JacksonFactory(), null)
            .setHttpRequestInitializer(retryHttpInitializerWrapper)
            .setApplicationName("test")
            .build();

    HttpRequest request = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
    HttpResponse response = request.execute();

    assertThat(mockSleeper.getCount(), equalTo(1));
    assertThat(response.getStatusCode(), equalTo(200));
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:22,代碼來源:RetryHttpInitializerWrapperTests.java

示例7: getTubeService

import com.google.api.client.http.HttpRequest; //導入依賴的package包/類
private synchronized YouTube getTubeService()
{
	if( tubeService == null )
	{
		tubeService = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(),
			new HttpRequestInitializer()
			{
				@Override
				public void initialize(HttpRequest request) throws IOException
				{
					// Nothing?
				}
			}).setApplicationName(EQUELLA).build();
	}
	return tubeService;
}
 
開發者ID:equella,項目名稱:Equella,代碼行數:17,代碼來源:GoogleServiceImpl.java

示例8: connect

import com.google.api.client.http.HttpRequest; //導入依賴的package包/類
@Override
protected Drive connect(final HostKeyCallback callback, final LoginCallback prompt) {
    authorizationService = new OAuth2RequestInterceptor(builder.build(this, prompt).build(), host.getProtocol())
        .withRedirectUri(host.getProtocol().getOAuthRedirectUrl());
    final HttpClientBuilder configuration = builder.build(this, prompt);
    configuration.addInterceptorLast(authorizationService);
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(authorizationService));
    this.transport = new ApacheHttpTransport(configuration.build());
    return new Drive.Builder(transport, json, new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest request) throws IOException {
            request.setSuppressUserAgentSuffix(true);
            // OAuth Bearer added in interceptor
        }
    })
        .setApplicationName(useragent.get())
        .build();
}
 
開發者ID:iterate-ch,項目名稱:cyberduck,代碼行數:19,代碼來源:DriveSession.java

示例9: YouTubeSingleton

import com.google.api.client.http.HttpRequest; //導入依賴的package包/類
private YouTubeSingleton() {

        credential = GoogleAccountCredential.usingOAuth2(
                YTApplication.getAppContext(), Arrays.asList(SCOPES))
                .setBackOff(new ExponentialBackOff());

        youTube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
            @Override
            public void initialize(HttpRequest httpRequest) throws IOException {

            }
        }).setApplicationName(YTApplication.getAppContext().getString(R.string.app_name))
                .build();

        youTubeWithCredentials = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), credential)
                .setApplicationName(YTApplication.getAppContext().getString(R.string.app_name))
                .build();
    }
 
開發者ID:pawelpaszki,項目名稱:youtube_background_android,代碼行數:19,代碼來源:YouTubeSingleton.java

示例10: getUserInfoJson

import com.google.api.client.http.HttpRequest; //導入依賴的package包/類
private User getUserInfoJson(final String authCode) throws IOException {
    try {
        final GoogleTokenResponse response = flow.newTokenRequest(authCode)
                .setRedirectUri(getCallbackUri())
                .execute();
        final Credential credential = flow.createAndStoreCredential(response, null);
        final HttpRequest request = HTTP_TRANSPORT.createRequestFactory(credential)
                .buildGetRequest(new GenericUrl(USER_INFO_URL));
        request.getHeaders().setContentType("application/json");
        final JSONObject identity = 
                new JSONObject(request.execute().parseAsString());
        return new User(
                identity.getString("id"),
                identity.getString("email"),
                identity.getString("name"),
                identity.getString("picture"));
    } catch (JSONException ex) {
        Logger.getLogger(AuthenticationResource.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}
 
開發者ID:PacktPublishing,項目名稱:Java-9-Programming-Blueprints,代碼行數:22,代碼來源:AuthenticationResource.java

示例11: ServiceConfigSupplier

import com.google.api.client.http.HttpRequest; //導入依賴的package包/類
@VisibleForTesting
ServiceConfigSupplier(
    Environment environment,
    HttpTransport httpTransport,
    JsonFactory jsonFactory,
    final GoogleCredential credential) {
  this.environment = environment;
  HttpRequestInitializer requestInitializer = new HttpRequestInitializer() {
    @Override
    public void initialize(HttpRequest request) throws IOException {
      request.setThrowExceptionOnExecuteError(false);
      credential.initialize(request);
    }
  };
  this.serviceManagement =
      new ServiceManagement.Builder(httpTransport, jsonFactory, requestInitializer)
          .setApplicationName("Endpoints Frameworks Java")
          .build();
}
 
開發者ID:cloudendpoints,項目名稱:endpoints-management-java,代碼行數:20,代碼來源:ServiceConfigSupplier.java

示例12: hasMetadataServer

import com.google.api.client.http.HttpRequest; //導入依賴的package包/類
private static boolean hasMetadataServer(HttpTransport transport) {
  try {
    HttpRequest request = transport.createRequestFactory()
        .buildGetRequest(new GenericUrl(METADATA_SERVER_URL));
    HttpResponse response = request.execute();
    HttpHeaders headers = response.getHeaders();
    return "Google".equals(headers.getFirstHeaderStringValue("Metadata-Flavor"));
  } catch (IOException | RuntimeException expected) {
    // If an error happens, it's probably safe to say the metadata service isn't available where
    // the code is running. We have to catch ApiProxyException due to the new dev server returning
    // a different error for unresolvable hostnames. Due to not wanting to put a required
    // dependency on the App Engine SDK here, we catch the generic RuntimeException and do a
    // class name check.
    if (expected instanceof RuntimeException
        && !API_PROXY_EXCEPTION_CLASS_NAME.equals(expected.getClass().getName())
        && !REMOTE_API_EXCEPTION_CLASS_NAME.equals(expected.getClass().getName())) {
      throw (RuntimeException) expected;
    }
  }
  return false;
}
 
開發者ID:cloudendpoints,項目名稱:endpoints-management-java,代碼行數:22,代碼來源:ControlFilter.java

示例13: postRequest

import com.google.api.client.http.HttpRequest; //導入依賴的package包/類
protected <E> E postRequest(String path, Object body, Class<E> responseType){
    try {
        URI uri = uri(path);
        GenericUrl url = new GenericUrl(uri);

        if ( logger.isDebugEnabled() ){
            logger.debug("Request POSTed into botframework api " + uri + ":");
            logger.debug(JSON_FACTORY.toPrettyString(body));
        }
        HttpContent content = new JsonHttpContent(JSON_FACTORY,body);
        HttpRequest request = requestFactory.buildPostRequest(url,content);
        E response = (E) request.execute().parseAs(responseType);
        if ( logger.isDebugEnabled() ){
            logger.debug("Response back from botframework api:");
            logger.debug(JSON_FACTORY.toPrettyString(response));
        }
        return response;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
開發者ID:bots4j,項目名稱:msbotframework,代碼行數:22,代碼來源:ConnectorClient.java

示例14: postRequestAsync

import com.google.api.client.http.HttpRequest; //導入依賴的package包/類
protected Future<HttpResponse> postRequestAsync(String path, Object body){
    try {
        URI uri = uri(path);
        GenericUrl url = new GenericUrl();
        if ( logger.isDebugEnabled() ){
            logger.debug("Request POSTed into botframework api " + uri + ":");
            logger.debug(JSON_FACTORY.toPrettyString(body));
        }
        HttpContent content = new JsonHttpContent(JSON_FACTORY,body);
        HttpRequest request = requestFactory.buildPostRequest(url,content);
        if ( this.executor != null ){
            return request.executeAsync(this.executor);
        }
        else{
            return request.executeAsync();
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
開發者ID:bots4j,項目名稱:msbotframework,代碼行數:22,代碼來源:ConnectorClient.java

示例15: YouTubeSingleton

import com.google.api.client.http.HttpRequest; //導入依賴的package包/類
private YouTubeSingleton(Context context)
{
    String appName = context.getString(R.string.app_name);
    credential = GoogleAccountCredential
            .usingOAuth2(context, Arrays.asList(SCOPES))
            .setBackOff(new ExponentialBackOff());

    youTube = new YouTube.Builder(
            new NetHttpTransport(),
            new JacksonFactory(),
            new HttpRequestInitializer()
            {
                @Override
                public void initialize(HttpRequest httpRequest) throws IOException {}
            }
    ).setApplicationName(appName).build();

    youTubeWithCredentials = new YouTube.Builder(
            new NetHttpTransport(),
            new JacksonFactory(),
            credential
    ).setApplicationName(appName).build();
}
 
開發者ID:teocci,項目名稱:YouTube-In-Background,代碼行數:24,代碼來源:YouTubeSingleton.java


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