Java 类com.google.api.client.http.HttpRequest 实例源码

项目:firebase-admin-java    文件:FirebaseInstanceId.java   
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;
    }
  });
}
项目:firebase-admin-java    文件:FirebaseAuthIT.java   
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();
  }
}
项目:elasticsearch_my    文件:GoogleCloudStorageService.java   
@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);
            }
    );
}
项目:elasticsearch_my    文件:RetryHttpInitializerWrapperTests.java   
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));
}
项目:elasticsearch_my    文件:RetryHttpInitializerWrapperTests.java   
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));
}
项目:Equella    文件:GoogleServiceImpl.java   
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;
}
项目:cyberduck    文件:DriveSession.java   
@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();
}
项目:youtube_background_android    文件:YouTubeSingleton.java   
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();
    }
项目:Java-9-Programming-Blueprints    文件:AuthenticationResource.java   
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;
    }
}
项目:endpoints-management-java    文件:ServiceConfigSupplier.java   
@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();
}
项目:endpoints-management-java    文件:ControlFilter.java   
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;
}
项目:msbotframework    文件:ConnectorClient.java   
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);
    }
}
项目:msbotframework    文件:ConnectorClient.java   
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);
    }
}
项目:YouTube-In-Background    文件:YouTubeSingleton.java   
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();
}
项目:zefiro    文件:NodeService.java   
/**
 * Recupera le definizioni di thumbnail valide per il contenuto.
 * 
 * @param pContentId
 *            L'id del contenuto.
 * 
 * @return La lista delle definizioni valide.
 * 
 * @throws IOException
 */
public List<String> getThumbnailDefinitions(String pContentId) throws IOException {
    /*
     * GET <base>/content{property}/thumbnaildefinitions
     */

    GenericUrl lUrl = getContentUrl(pContentId);
    lUrl.appendRawPath(URL_RELATIVE_THUMBNAIL_DEFINITIONS);

    HttpRequest lRequest = mHttpRequestFactory.buildGetRequest(lUrl);
    TypeReference<List<String>> lType = new TypeReference<List<String>>() {};
    @SuppressWarnings("unchecked")
    List<String> lResponse = (List<String>) lRequest.execute().parseAs(lType.getType());

    return lResponse;
}
项目:zefiro    文件:AlfrescoHelper.java   
public static List<Person> getUsers(HttpRequestFactory pHttpRequestFactory, AlfrescoConfig pConfig) {
    mLog.debug("START getUsers()");

    // FIXME (Alessio): Alfresco non supporta questo metodo!

    PeopleUrl lPeopleUrl = new PeopleUrl(pConfig.getHost());
    try {
        HttpRequest lRequest = pHttpRequestFactory.buildGetRequest(lPeopleUrl);
        @SuppressWarnings("unchecked")
        MultipleEntry<Person> lResponse =
                (MultipleEntry<Person>) lRequest.execute().parseAs(
                        (new TypeReference<MultipleEntry<Person>>() {}).getType());
        mLog.debug("END getUsers()");
        return lResponse.getEntries();

    } catch (Exception e) {
        // TODO (Alessio): gestione decente delle eccezioni
        mLog.error("Unexpected failure", e);
        throw new AlfrescoException(e, AlfrescoException.GENERIC_EXCEPTION);
    }
}
项目:zefiro    文件:AlfrescoHelper.java   
public static Person getUser(String pStrUserId, HttpRequestFactory pHttpRequestFactory, AlfrescoConfig pConfig) {
    mLog.debug("START getUser(String)");

    PeopleUrl lPeopleUrl = new PeopleUrl(pConfig.getHost());
    lPeopleUrl.setUserId(pStrUserId);
    try {
        HttpRequest lRequest = pHttpRequestFactory.buildGetRequest(lPeopleUrl);

        @SuppressWarnings("unchecked")
        SingleEntry<Person> lResponse =
                (SingleEntry<Person>) lRequest.execute().parseAs(
                        (new TypeReference<SingleEntry<Person>>() {}).getType());
        mLog.debug("END getUser(String)");
        return lResponse.getEntry();

    } catch (Exception e) {
        mLog.error("Unexpected failure", e);
        throw new AlfrescoException(e, AlfrescoException.GENERIC_EXCEPTION);
    }
}
项目:zefiro    文件:AlfrescoHelper.java   
public static GroupsList getGroups(HttpRequestFactory pHttpRequestFactory, AlfrescoConfig pConfig) {
    mLog.debug("START getGroups()");

    GroupsUrl lUrl = new GroupsUrl(pConfig.getHost());
    try {
        HttpRequest lRequest = pHttpRequestFactory.buildGetRequest(lUrl);
        GroupsList lResponse = lRequest.execute().parseAs(GroupsList.class);
        mLog.debug("END getGroups()");
        return lResponse;

    } catch (Exception e) {
        // TODO (Alessio): gestione decente delle eccezioni
        mLog.error("Unexpected failure", e);
        throw new AlfrescoException(e, AlfrescoException.GENERIC_EXCEPTION);
    }
}
项目:Android-YouTube-Background-Player    文件:YouTubeSingleton.java   
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();
    }
项目:nlu-api-client-java    文件:UnsuccessfulResponseHandler.java   
/**
 * Handler that will be invoked when an error response is received.
 * 
 * @param request Instance of {@link HttpRequest}
 * @param response Instance of {@link HttpResponse}
 * @param supportsRetry Flag that indicates whether there will be a retry if this handler
 * returns true. 
 */
@Override
public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry)
        throws IOException {    

    IOException exception;

    try {
        String responseString = response.parseAsString();

        ErrorMessage msg = jsonFactory.fromString(responseString, ErrorMessage.class);

        exception = new ApiException(msg);
    } catch (IOException e) {
        String errorMessage = "Couldn't parse JSON error message: " + e.getMessage();

        logger.severe(errorMessage);

        exception = new ApiException(errorMessage);
    }

    throw exception;
}
项目:endpoints-java    文件:GoogleAuthTest.java   
private HttpRequest constructHttpRequest(final String content) throws IOException {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
          result.setContentType("application/json");
          result.setContent(content);
          return result;
        }
      };
    }
  };
  return transport.createRequestFactory().buildGetRequest(new GenericUrl("https://google.com"))
      .setParser(new JsonObjectParser(new JacksonFactory()));
}
项目:gateplugin-Tagger_GoogleNLP    文件:TaggerGoogleNLP.java   
/**
 * Get an instance of the language service.
 *
 * @param document
 * @return
 */
public CloudNaturalLanguageAPI getApiService(GoogleCredential credential) {
  final GoogleCredential cred = credential;
  CloudNaturalLanguageAPI api = null;
  try {
    api = new CloudNaturalLanguageAPI.Builder(
            GoogleNetHttpTransport.newTrustedTransport(),
            JacksonFactory.getDefaultInstance(),
            new HttpRequestInitializer() {
      @Override
      public void initialize(HttpRequest httpRequest) throws IOException {
        cred.initialize(httpRequest);
      }
    }).setApplicationName(getApplicationName()).build();
  } catch (Exception ex) {
    throw new GateRuntimeException("Could not establish Google Service API", ex);
  }
  //System.err.println("DEBUG: API instance established: " + api);
  return api;
}
项目:copybara    文件:GitHubApiTransportImpl.java   
@SuppressWarnings("unchecked")
@Override
public <T> T post(String path, Object request, Type responseType)
    throws RepoException, ValidationException {
  HttpRequestFactory requestFactory = getHttpRequestFactory(getCredentials());

  GenericUrl url = new GenericUrl(URI.create(API_URL + "/" + path));
  try {
    HttpRequest httpRequest = requestFactory.buildPostRequest(url,
        new JsonHttpContent(JSON_FACTORY, request));
    HttpResponse response = httpRequest.execute();
    return (T) response.parseAs(responseType);
  } catch (IOException e) {
    throw new RepoException("Error running GitHub API operation " + path, e);
  }
}
项目:Spectra    文件:YoutubeSearcher.java   
public YoutubeSearcher(String apiKey)
{
    youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), (HttpRequest request) -> {
    }).setApplicationName(SpConst.BOTNAME).build();
    Search.List tmp = null;
    try {
        tmp = youtube.search().list("id,snippet");
    } catch (IOException ex) {
        SimpleLog.getLog("Youtube").fatal("Failed to initialize search: "+ex.toString());
    }
    search = tmp;
    if(search!=null)
    {
        search.setKey(apiKey);
        search.setType("video");
        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
    }
}
项目:http-monitor    文件:HttpClient.java   
public String get(String url) {
    try {
        HttpRequest request = new NetHttpTransport()
                .createRequestFactory()
                .buildGetRequest(new GenericUrl(url));
        HttpResponse response = request.execute();
        InputStream is = response.getContent();
        StringBuilder sb = new StringBuilder();
        int ch;
        while ((ch = is.read()) != -1) {
            sb.append((char) ch);
        }
        response.disconnect();
        return sb.toString();
    } catch (Exception e) {
        throw new RuntimeException();
    }
}
项目:beam    文件:RetryHttpRequestInitializer.java   
@Override
public boolean handleIOException(HttpRequest request, boolean supportsRetry)
    throws IOException {
  // We will retry if the request supports retry or the backoff was successful.
  // Note that the order of these checks is important since
  // backOffWasSuccessful will perform a sleep.
  boolean willRetry = supportsRetry && backOffWasSuccessful(ioExceptionBackOff);
  if (willRetry) {
    ioExceptionRetries += 1;
    LOG.debug("Request failed with IOException, will retry: {}", request.getUrl());
  } else {
    String message = "Request failed with IOException, "
        + "performed {} retries due to IOExceptions, "
        + "performed {} retries due to unsuccessful status codes, "
        + "HTTP framework says request {} be retried, "
        + "(caller responsible for retrying): {}";
    LOG.warn(message,
        ioExceptionRetries,
        unsuccessfulResponseRetries,
        supportsRetry ? "can" : "cannot",
        request.getUrl());
  }
  return willRetry;
}
项目:beam    文件:RetryHttpRequestInitializer.java   
@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);
  }
}
项目:Wiab.pro    文件:GoogleAuthentication.java   
public static String getClientEmail(String accessToken) throws IOException {
  /*
   * Get loggined user info as described in
   * https://developers.google.com/accounts/docs/OAuth2Login#userinfocall
   */
  GenericUrl url = new GenericUrl("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken);
  HttpRequest request = HTTP_REQUEST_FACTORY.buildGetRequest(url);
  HttpResponse response = request.execute();
  if (!response.isSuccessStatusCode()) {
    throw new IOException(response.getStatusMessage());
  }
  JsonElement jsonElement = new JsonParser().parse(new InputStreamReader(response.getContent(), "utf-8"));
  JsonObject jsonObj = jsonElement.getAsJsonObject();
  return jsonObj.get("email").getAsString();
}
项目:gaso    文件:GooglePlaces.java   
public Station getStationDetails(Station station) throws Exception {
    try {

        HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
        HttpRequest request = httpRequestFactory
                .buildGetRequest(new GenericUrl(PLACES_DETAILS_URL));
        request.getUrl().put("key", API_KEY);
        request.getUrl().put("reference", station.getReference());
        request.getUrl().put("sensor", "false");

        String place = request.execute().parseAsString();

        return parser.stationFromJson(station, place);

    } catch (HttpResponseException e) {
        Log.e("ErrorDetails", e.getMessage());
        throw e;
    }
}
项目:nomulus    文件:DirectoryGroupsConnectionTest.java   
/** Returns a valid GoogleJsonResponseException for the given status code and error message.  */
private GoogleJsonResponseException makeResponseException(
    final int statusCode,
    final String message) throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(statusCode);
          response.setContentType(Json.MEDIA_TYPE);
          response.setContent(String.format(
              "{\"error\":{\"code\":%d,\"message\":\"%s\",\"domain\":\"global\","
              + "\"reason\":\"duplicate\"}}",
              statusCode,
              message));
          return response;
        }};
    }};
  HttpRequest request = transport.createRequestFactory()
      .buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL)
      .setThrowExceptionOnExecuteError(false);
  return GoogleJsonResponseException.from(new JacksonFactory(), request.execute());
}
项目:nearby-places    文件:GooglePlaces.java   
/**
 * Searching single place full details
 * @param reference - reference id of place
 *                 - which you will get in search api request
 * */
public PlaceDetails getPlaceDetails(String reference) throws Exception {
    try {

        HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
        HttpRequest request = httpRequestFactory
                .buildGetRequest(new GenericUrl(PLACES_DETAILS_URL));
        request.getUrl().put("key", API_KEY);
        request.getUrl().put("reference", reference);
        request.getUrl().put("sensor", "false");

        PlaceDetails place = request.execute().parseAs(PlaceDetails.class);

        return place;

    } catch (HttpResponseException e) {
        Log.e("Error in Perform Details", e.getMessage());
        throw e;
    }
}
项目:Reminders    文件:Reminders.java   
public static Tasks getGoogleTasksService(final Context context, String accountName) {
    final GoogleAccountCredential credential =
            GoogleAccountCredential.usingOAuth2(context, ListManager.TASKS_SCOPES);
    credential.setSelectedAccountName(accountName);
    Tasks googleService =
        new Tasks.Builder(TRANSPORT, JSON_FACTORY, credential)
                 .setApplicationName(DateUtils.getAppName(context))
                 .setHttpRequestInitializer(new HttpRequestInitializer() {
                     @Override
                     public void initialize(HttpRequest httpRequest) {
                         credential.initialize(httpRequest);
                         httpRequest.setConnectTimeout(3 * 1000);  // 3 seconds connect timeout
                         httpRequest.setReadTimeout(3 * 1000);  // 3 seconds read timeout
                     }
                 })
                 .build();
    return googleService;
}
项目:postmen-sdk-java    文件:RateLimitExecuteInterceptor.java   
public void intercept(HttpRequest request) throws IOException {
    rateLimit.decrementRateCount();
    System.out.println("This is the rateCount " + rateLimit.getRateCount());
    System.out.println("This is the resetTime " + rateLimit.getResetTime());
    if (rateLimit.getRateCount() < 0) {
        System.out.println("RateLimit Exceeded, computing next call");
        long timeNow = Calendar.getInstance().getTimeInMillis();
        if(timeNow < rateLimit.getResetTime()) {
            BackOff backOff = new RateLimitBackOff(timeNow, rateLimit);
            System.out.println("delay call (from interceptor) " + backOff.nextBackOffMillis());
            try {
                BackOffUtils.next(sleeper, backOff);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
项目:postmen-sdk-java    文件:PostmenUnsuccessfulResponseHandlerTest.java   
@Test
public void testHandleResponse() {
    HttpRequest req;
    try {
        req = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
        req.setNumberOfRetries(5);
        LabelResponse labelResponse = new LabelResponse();
        Meta meta = new Meta();
        meta.setCode(200);
        meta.setRetryable(true);
        labelResponse.setMeta(meta);
        Boolean retry = responseHandler.handleResponse(req, labelResponse, true);
        assertTrue(retry);
        assertEquals(new Long(1000), sleeper.getDelay());
        //responseHandler.handleResponse(req, labelResponse, true);
    } catch (IOException e) {
    }   
}
项目:postmen-sdk-java    文件:PostmenUnsuccessfulResponseHandlerTest.java   
@Test
public void testExponentialDelay() {
    HttpRequest req;
    try {
        req = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
        req.setNumberOfRetries(5);
        LabelResponse labelResponse = new LabelResponse();
        Meta meta = new Meta();
        meta.setCode(200);
        meta.setRetryable(true);
        labelResponse.setMeta(meta);
        Boolean retry = null;
        Long delay = new Long(1000);
        for(int i = 0; i < 5; i++) {
            retry = responseHandler.handleResponse(req, labelResponse, true);
            assertEquals(delay, sleeper.getDelay());
            delay *= 2;
        }
        assertTrue(retry);

        //responseHandler.handleResponse(req, labelResponse, true);
    } catch (IOException e) {
    }   
}
项目:GeoNote    文件:GooglePlaces.java   
public PlaceDetails getPlaceDetails(Place place) throws Exception {
    try {
        System.out.println("Perform Place Detail....");
        HttpRequestFactory httpRequestFactory = createRequestFactory(transport);
        HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_DETAILS_URL));

        request.getUrl().put("key", this.apiKey);
        request.getUrl().put("reference", place.reference);
        request.getUrl().put("sensor", "false");

        if (PRINT_AS_STRING) {
            System.out.println(request.execute().parseAsString());
        } else {
            PlaceDetails placeDetails = request.execute().parseAs(PlaceDetails.class);
            System.out.println(placeDetails);
            return placeDetails;
        }

    } catch (HttpResponseException e) {
        System.err.println(e.getStatusMessage());
        throw e;
    }

    return null;
}
项目:postmen-sdk-java    文件:PostmenUnsuccessfulResponseHandlerTest.java   
@Test
public void testNotRetryable() {
    HttpRequest req;
    try {
        req = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
        req.setNumberOfRetries(5);
        LabelResponse labelResponse = new LabelResponse();
        Meta meta = new Meta();
        meta.setCode(200);
        meta.setRetryable(false);
        labelResponse.setMeta(meta);
        Boolean retry = null;
        retry = responseHandler.handleResponse(req, labelResponse, true);
        assertFalse(retry);

        //responseHandler.handleResponse(req, labelResponse, true);
    } catch (IOException e) {
    }   
}
项目:postmen-sdk-java    文件:PostmenUnsuccessfulResponseHandlerTest.java   
@Test
public void testRetryableNullInResponse() {
    HttpRequest req;
    try {
        req = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
        req.setNumberOfRetries(5);
        LabelResponse labelResponse = new LabelResponse();
        Meta meta = new Meta();
        meta.setCode(200);
        meta.setRetryable(null);
        labelResponse.setMeta(meta);
        Boolean retry = null;
        retry = responseHandler.handleResponse(req, labelResponse, true);
        assertFalse(retry);

        //responseHandler.handleResponse(req, labelResponse, true);
    } catch (IOException e) {
    }   
}
项目:postmen-sdk-java    文件:PostmenUnsuccessfulResponseHandlerTest.java   
@Test
public void testDoNotRetry() {
    HttpRequest req;
    try {
        req = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
        req.setNumberOfRetries(5);
        LabelResponse labelResponse = new LabelResponse();
        Meta meta = new Meta();
        meta.setCode(200);
        meta.setRetryable(true);
        labelResponse.setMeta(meta);
        Boolean retry = null;
        retry = responseHandler.handleResponse(req, labelResponse, false);
        assertFalse(retry);

        //responseHandler.handleResponse(req, labelResponse, true);
    } catch (IOException e) {
    }   
}
项目:onedrive-java-client    文件:OneDriveAuthorisationProvider.java   
private void getTokenFromCode(final String code) throws IOException {

        log.debug("Fetching authorisation token using authorisation code");
        HttpRequest request =
                HTTP_TRANSPORT.createRequestFactory().buildGetRequest(new GenericUrl("https://login.live.com/oauth20_token.srf") {
                    @Key("client_id")
                    private String id = clientId;
                    @Key("client_secret")
                    private String secret = clientSecret;
                    @Key("code")
                    private String authCode = code;
                    @Key("grant_type")
                    private String grantType = "authorization_code";
                    @Key("redirect_uri")
                    private String redirect = "https://login.live.com/oauth20_desktop.srf";
                });

        request.setParser(new JsonObjectParser(JSON_FACTORY));

        processResponse(request.execute());
    }