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

项目:coala    文件:DealOAuth1Util.java   
/**
 * Post an order using the token and secret token to authenticate in DEAL.
 * To demonstrate successful authentication a POST request is executed.
 * 
 * @param messageToBePosted the JSON string representing the order
 * @return the result of the post action
 * 
 * @throws Exception on an exception occurring
 */
public static String PostOrderWithTokensOnly(String messageToBePosted)
        throws Exception
{
    // utilize accessToken to access protected resource in DEAL
    HttpRequestFactory factory = TRANSPORT
            .createRequestFactory(getParameters());
    GenericUrl url = new GenericUrl(PROTECTED_ORDERS_URL);
    InputStream stream = new ByteArrayInputStream(
            messageToBePosted.getBytes());
    InputStreamContent content = new InputStreamContent(JSON_IDENTIFIER,
            stream);
    HttpRequest req = factory.buildPostRequest(url, content);

    HttpResponse resp = req.execute();
    String response = resp.parseAsString();

    // log the response
    if (resp.getStatusCode() != 200 && LOG.isInfoEnabled())
    {
        LOG.info("Response Status Code: " + resp.getStatusCode());
        LOG.info("Response body:" + response);
    }

    return response;
}
项目:Xero-Java    文件:OAuthAccessToken.java   
public OAuthAccessToken build() throws IOException {
  Url = new GenericUrl(config.getAccessTokenUrl());

  transport = new ApacheHttpTransport();

  HttpRequestFactory requestFactory = transport.createRequestFactory();
  request = requestFactory.buildRequest(HttpMethods.GET, Url, null);

  HttpHeaders headers = new HttpHeaders();
  headers.setUserAgent(config.getUserAgent());
  headers.setAccept(config.getAccept());

  request.setHeaders(headers);
  createRefreshParameters().intercept(request);

  return this;
}
项目: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);
    }
}
项目:ftc    文件:RestApi.java   
public String executeStmt(String method, String urlString, String statement, List<NameValuePair> qparams)
        throws IOException {
    Check.notNull(statement);

    GenericUrl url = setParams(new GenericUrl(urlString), qparams);
    UrlEncodedContent urlEntity = setMediaType(getUrlEncodedSql(statement));

    HttpRequestFactory rf = httpTransport.createRequestFactory(credential);

    HttpResponse response = rf.buildRequest(method, url, urlEntity).execute();
    String result = readGoogleResponse(response);

    if (response.getStatusCode() != HttpServletResponse.SC_OK)
        throw new RuntimeException(result.toString() + statement);

    return result;
}
项目: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);
  }
}
项目:copybara    文件:GerritApiTransportImpl.java   
/**
 * TODO(malcon): Consolidate GitHub and this one in one class
 */
private HttpRequestFactory getHttpRequestFactory(@Nullable UserPassword userPassword)
    throws RepoException, ValidationException {
  return httpTransport.createRequestFactory(
      request -> {
        request.setConnectTimeout((int) Duration.ofMinutes(1).toMillis());
        request.setReadTimeout((int) Duration.ofMinutes(1).toMillis());
        HttpHeaders httpHeaders = new HttpHeaders();
        if (userPassword != null) {
          httpHeaders.setBasicAuthentication(userPassword.getUsername(),
                                             userPassword.getPassword_BeCareful());
        }
        request.setHeaders(httpHeaders);
        request.setParser(new JsonObjectParser(JSON_FACTORY));
      });
}
项目: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;
    }
}
项目: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;
    }
}
项目:postmen-sdk-java    文件:HandlerTest.java   
@Before
public void setUp() throws ConfigException {
    config = new ConfigBuilder().setRegion("sandbox").setApiKey("someApiKey").build();
    handler = new Handler(config) {
        @Override
        public <T extends Response> T execute(HttpRequestFactory requestFactory, String method, PostmenUrl endpoint, Object body, Class<T> type) throws IOException {
            T c = null;
            try {
                c = type.newInstance();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return c;
        }
    };
}
项目:postmen-sdk-java    文件:HandlerTest.java   
@Test
public void testCallAsString() {
    IOException ex = null;
    handler = new Handler(config) {
        @Override
        public <T extends Response> T execute(HttpRequestFactory requestFactory, String method, PostmenUrl endpoint, Object body, Class<T> type) throws IOException {
            MapResponse response = new MapResponse();
            response.setData(new HashMap<Object, Object>());
            return (T) response;
        }
    };
    try {
        String response = handler.callAndParseAsString(null, null, null);
        assertNotNull(response);
    } catch (IOException e) {
        ex = e;
    }
    assertNull(ex);
}
项目:health-vis    文件:FitbitCacheController.java   
@Scheduled(fixedRate = MONTHLY, initialDelay = MONTHLY)
@RequestMapping(value = "/cache", method = RequestMethod.DELETE)
@ResponseBody
public String addAllToCacheQueue() throws IOException, FitbitClientException {
    HttpRequestFactory requestFactory = getHttpRequestFactory();

    FitbitUserClient userRepo = new FitbitUserClient(requestFactory);

    LocalDate firstDate = userRepo.getAuthorisedUser().getMemberSince();
    LocalDate today = LocalDate.now();
    for (LocalDate date : new LocalDateRange(firstDate, today)) {
        if (!cacheQueue.contains(date)) {
            cacheQueue.add(date);
        }
    }
    return "cache cleared";
}
项目:health-vis    文件:FitbitCacheController.java   
@Scheduled(fixedRate = HOURLY, initialDelay = IMMEDIATE)
public void updateCacheQueue() throws IOException, FitbitClientException {

    HttpRequestFactory requestFactory = getHttpRequestFactory();

    FitbitUserClient userRepo = new FitbitUserClient(requestFactory);

    LocalDate firstDate = userRepo.getAuthorisedUser().getMemberSince();
    LocalDate today = LocalDate.now();

    for (LocalDate date : new LocalDateRange(firstDate, today)) {
        if (!activityService.hasCompleteEntry(date)
                || date.isAfter(today.minusDays(FORCE_UPDATE_THRESHOLD_DAYS))) {
            if (!cacheQueue.contains(date)) {
                cacheQueue.add(date);
            }
        }
    }
}
项目:health-vis    文件:FitbitCacheController.java   
@Scheduled(cron = "0 0 * * * *")
@Async
public void cacheFitbitData() throws IOException, FitbitClientException {

    logger.info("refreshing cache");

    HttpRequestFactory requestFactory = getHttpRequestFactory();

    FitbitIntradayActivityClient intradayActivityDao = new FitbitIntradayActivityClient(requestFactory);

    DayActivityFitbitToEntity transformer = new DayActivityFitbitToEntity();

    ListIterator<LocalDate> listIterator = cacheQueue.listIterator();
    while (listIterator.hasNext()) {
        LocalDate date = listIterator.next();
        logger.info("getting activity from fitbit for " + date.toString());
        FitbitIntradayActivity activity = intradayActivityDao.getDayActivity(date);
        logger.info("replacing activity for " + date.toString());
        activityService.replaceActivities(transformer.transform(activity));

        listIterator.remove();
    }

}
项目:hygieia-temp    文件:JiraDataFactoryImpl.java   
/**
 * Runs the jira-client library tools against a given REST-formatted query.
 * This requires a pre-formatted paged query to run, and will not perform
 * the paging for you - there are other helper methods for this.
 *
 * @return A formatted JSONArray response
 */
@SuppressWarnings("unchecked")
public JSONArray getPagingQueryResponse() {
    JSONArray mainMsg = new JSONArray();
    JSONObject innerObj = new JSONObject();
    HttpRequestFactory rqFactory = jiraConnection.generateRequestFactory();
    LOGGER.debug(this.pagingQuery);
    JSONObject response = jiraConnection.getResponse(rqFactory,
            this.getPagingQuery());

    innerObj.put("issues", response.get("issues"));
    mainMsg.add(innerObj.get("issues"));

    mainMsg.add(response);
    return mainMsg;
}
项目:providence    文件:HttpClientHandlerNetworkTest.java   
@Test
public void testBrokenPipe_NetHttpTransport() throws Failure {
    HttpRequestFactory factory = new NetHttpTransport().createRequestFactory();

    TestService.Iface client = new TestService.Client(new HttpClientHandler(
            this::endpoint, factory, provider));

    try {
        // The request must be larger than the socket read buffer, to force it to fail the write to socket.
        client.test(new Request(Strings.times("request ", 1024 * 1024)));
        fail("No exception");
    } catch (HttpResponseException e) {
        fail("When did this become a HttpResponseException?");
    } catch (IOException ex) {
        // TODO: This should be a HttpResponseException
        assertThat(ex.getMessage(), is("Error writing request body to server"));
    }
}
项目:providence    文件:HttpClientHandlerNetworkTest.java   
@Test
public void testBrokenPipe_ApacheHttpTransport() throws IOException, Failure {
    HttpRequestFactory factory = new ApacheHttpTransport().createRequestFactory();

    TestService.Iface client = new TestService.Client(new HttpClientHandler(
            this::endpoint, factory, provider));

    try {
        // The request must be larger than the socket read buffer, to force it to fail the write to socket.
        client.test(new Request(Strings.times("request ", 1024 * 1024)));
        fail("No exception");
    } catch (SocketException ex) {
        // TODO: This should be a HttpResponseException
        assertThat(ex.getMessage(), anyOf(
                containsString("Broken pipe"),
                is("Connection reset"),
                is("Software caused connection abort: socket write error")));
    }
}
项目:java-docs-samples    文件:BuildIapRequest.java   
private static String getGoogleIdToken(String jwt) throws Exception {
  final GenericData tokenRequest =
      new GenericData().set("grant_type", JWT_BEARER_TOKEN_GRANT_TYPE).set("assertion", jwt);
  final UrlEncodedContent content = new UrlEncodedContent(tokenRequest);

  final HttpRequestFactory requestFactory = httpTransport.createRequestFactory();

  final HttpRequest request =
      requestFactory
          .buildPostRequest(new GenericUrl(OAUTH_TOKEN_URI), content)
          .setParser(new JsonObjectParser(JacksonFactory.getDefaultInstance()));

  HttpResponse response;
  String idToken = null;
  response = request.execute();
  GenericData responseData = response.parseAs(GenericData.class);
  idToken = (String) responseData.get("id_token");
  return idToken;
}
项目:java-docs-samples    文件:StorageSample.java   
/**
 * Fetches the listing of the given bucket.
 *
 * @param bucketName the name of the bucket to list.
 *
 * @return the raw XML containing the listing of the bucket.
 * @throws IOException if there's an error communicating with Cloud Storage.
 * @throws GeneralSecurityException for errors creating https connection.
 */
public static String listBucket(final String bucketName)
    throws IOException, GeneralSecurityException {
  //[START snippet]
  // Build an account credential.
  GoogleCredential credential = GoogleCredential.getApplicationDefault()
      .createScoped(Collections.singleton(STORAGE_SCOPE));

  // Set up and execute a Google Cloud Storage request.
  String uri = "https://storage.googleapis.com/"
      + URLEncoder.encode(bucketName, "UTF-8");

  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory(
      credential);
  GenericUrl url = new GenericUrl(uri);

  HttpRequest request = requestFactory.buildGetRequest(url);
  HttpResponse response = request.execute();
  String content = response.parseAsString();
  //[END snippet]

  return content;
}
项目:GeoNote    文件:DropletServer.java   
public void putDroplets(String userName, List<Droplet> droplets) throws Exception {
    try {
        System.out.println("Perform droplet search ....");
        HttpRequestFactory httpRequestFactory = createRequestFactory(transport);

        HttpContent content = new JsonHttpContent(new JacksonFactory(), droplets);
        HttpRequest request = httpRequestFactory.buildPostRequest(
                new GenericUrl(DROPLET_POST_URL + userName),
                content);

        HttpResponse response = request.execute();
        System.out.println(response.getStatusCode());

    } catch (HttpResponseException e) {
        System.err.println(e.getStatusMessage());
        throw 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;
}
项目:coala    文件:DealOAuth1Util.java   
/**
 * get a message using the token and secret token to authenticate in DEAL.
 * To demonstrate successfull authentication a POST request is executed.
 * 
 * @throws Exception on an exception occuring
 */
public static String getOrderWithTokensOnly(String urlToBeGet)
        throws Exception
{
    // utilize accessToken to access protected resource in DEAL
    HttpRequestFactory factory = TRANSPORT
            .createRequestFactory(getParameters());
    GenericUrl url = new GenericUrl(urlToBeGet);
    HttpRequest req = factory.buildGetRequest(url);

    HttpResponse resp = req.execute();
    req.getContent().writeTo(System.out);
    String responseString = resp.parseAsString();

    // Log
    if (LOG.isInfoEnabled())
    {
        LOG.info("Response Status Code: " + resp.getStatusCode());
        LOG.info("Response body:" + responseString);
    }

    return responseString;
}
项目:glass    文件:PlaceUtils.java   
private static List<Place> performSearch( String kind, String type, double lat, double lng )
    throws IOException
{
  HttpTransport httpTransport = new NetHttpTransport();
  HttpRequestFactory hrf = httpTransport.createRequestFactory();

  String paramsf = "%s?location=%f,%f&rankby=distance&keyword=%s&type=%s&sensor=true&key=%s";
  String params = String.format(paramsf, SearchData.BASE_URL, lat, lng, type, kind, AuthUtils.API_KEY);
  GenericUrl url = new GenericUrl(params);
  HttpRequest hreq = hrf.buildGetRequest(url);
  HttpResponse hres = hreq.execute();

  InputStream content = hres.getContent();
  JsonParser p = new JacksonFactory().createJsonParser(content);
  SearchData searchData = p.parse(SearchData.class, null);

  return searchData.buildPlaces();
}
项目:glass    文件:PlaceUtils.java   
private static Place populateDetails( Place place )
      throws IOException
  {
    // grab more restaurant details
    HttpTransport httpTransport = new NetHttpTransport();
    HttpRequestFactory hrf = httpTransport.createRequestFactory();

    String paramsf = "%s?reference=%s&sensor=true&key=%s";
    String params = String.format(paramsf, DetailsData.BASE_URL, place.getReference(), AuthUtils.API_KEY);
    GenericUrl url = new GenericUrl(params);
    HttpRequest hreq = hrf.buildGetRequest(url);
    HttpResponse hres = hreq.execute();

//    ByteArrayOutputStream os = new ByteArrayOutputStream();
//    IOUtils.copy(hres.getContent(), os, false);
//    System.out.println( os.toString() );

    InputStream content2 = hres.getContent();
    JsonParser p = new JacksonFactory().createJsonParser(content2);
    DetailsData details = p.parse(DetailsData.class, null);
    details.populatePlace( place );

    return place;
  }
项目:glass    文件:PlaceUtils.java   
private static List<Place> performSearch( String kind, String type, double lat, double lng )
    throws IOException
{
  HttpTransport httpTransport = new NetHttpTransport();
  HttpRequestFactory hrf = httpTransport.createRequestFactory();

  String paramsf = "%s?location=%f,%f&rankby=distance&keyword=%s&type=%s&sensor=true&key=%s";
  String params = String.format(paramsf, SearchData.BASE_URL, lat, lng, type, kind, AuthUtils.API_KEY);
  GenericUrl url = new GenericUrl(params);
  HttpRequest hreq = hrf.buildGetRequest(url);
  HttpResponse hres = hreq.execute();

  InputStream content = hres.getContent();
  JsonParser p = new JacksonFactory().createJsonParser(content);
  SearchData searchData = p.parse(SearchData.class, null);

  return searchData.buildPlaces();
}
项目:glass    文件:PlaceUtils.java   
private static Place populateDetails( Place place )
      throws IOException
  {
    // grab more restaurant details
    HttpTransport httpTransport = new NetHttpTransport();
    HttpRequestFactory hrf = httpTransport.createRequestFactory();

    String paramsf = "%s?reference=%s&sensor=true&key=%s";
    String params = String.format(paramsf, DetailsData.BASE_URL, place.getReference(), AuthUtils.API_KEY);
    GenericUrl url = new GenericUrl(params);
    HttpRequest hreq = hrf.buildGetRequest(url);
    HttpResponse hres = hreq.execute();

//    ByteArrayOutputStream os = new ByteArrayOutputStream();
//    IOUtils.copy(hres.getContent(), os, false);
//    System.out.println( os.toString() );

    InputStream content2 = hres.getContent();
    JsonParser p = new JacksonFactory().createJsonParser(content2);
    DetailsData details = p.parse(DetailsData.class, null);
    details.populatePlace( place );

    return place;
  }
项目:pdi-google-spreadsheet-plugin    文件:GoogleSpreadsheet.java   
public static String getAccessToken(String email, KeyStore pks) throws Exception {
    PrivateKey pk = getPrivateKey(pks);
    if (pk != null && !email.equals("")) {
        try {
            GoogleCredential credential = new GoogleCredential.Builder().setTransport(GoogleSpreadsheet.HTTP_TRANSPORT)
                    .setJsonFactory(GoogleSpreadsheet.JSON_FACTORY).setServiceAccountScopes(GoogleSpreadsheet.SCOPES).setServiceAccountId(email)
                    .setServiceAccountPrivateKey(pk).build();

            HttpRequestFactory requestFactory = GoogleSpreadsheet.HTTP_TRANSPORT.createRequestFactory(credential);
            GenericUrl url = new GenericUrl(GoogleSpreadsheet.getSpreadsheetFeedURL().toString());
            HttpRequest request = requestFactory.buildGetRequest(url);
            request.execute();
            return credential.getAccessToken();
        } catch (Exception e) {
            throw new Exception("Error fetching Access Token", e);
        }
    }
    return null;
}
项目:GeoNote    文件:DropletServer.java   
public void putDroplets(String userName, List<Droplet> droplets) throws Exception {
    try {
        System.out.println("Perform droplet search ....");
        HttpRequestFactory httpRequestFactory = createRequestFactory(transport);

        HttpContent content = new JsonHttpContent(new JacksonFactory(), droplets);
        HttpRequest request = httpRequestFactory.buildPostRequest(
                new GenericUrl(DROPLET_POST_URL + userName),
                content);

        HttpResponse response = request.execute();
        System.out.println(response.getStatusCode());

    } catch (HttpResponseException e) {
        System.err.println(e.getStatusMessage());
        throw 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;
}
项目:piezo    文件:HttpJsonRpcServerTest.java   
@Test
public void testMissingBody() throws IOException {
  HttpContent httpContent = new ByteArrayContent("application/json",
      new byte[]{});

  GenericUrl url = new GenericUrl();
  url.setScheme("http");
  url.setHost("localhost");
  url.setPort(port);
  url.setRawPath("/tox");

  HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  HttpRequest httpRequest = requestFactory.buildPostRequest(url, httpContent);

  HttpResponse httpResponse = httpRequest.execute();
  Assert.assertEquals(HttpStatusCodes.STATUS_CODE_OK, httpResponse.getStatusCode());
  Reader reader = new InputStreamReader(httpResponse.getContent(), Charsets.UTF_8);

  JsonRpcResponse response = JsonRpcResponse.fromJson(new JsonParser().parse(reader)
      .getAsJsonObject());

  Assert.assertTrue(response.isError());
  Assert.assertEquals(400, response.error().status().code());
}
项目:googleads-java-lib    文件:ReportRequestFactoryHelper.java   
/**
 * Gets the report HTTP URL connection given report URL and proper information needed to
 * authenticate the request.
 *
 * @param reportUrl the URL of the report response or download
 * @return the report HTTP URL connection
 * @throws AuthenticationException If OAuth authorization fails.
 */
@VisibleForTesting
HttpRequestFactory getHttpRequestFactory(final String reportUrl, String version)
    throws AuthenticationException {
  final HttpHeaders httpHeaders = createHeaders(reportUrl, version);
  return httpTransport.createRequestFactory(new HttpRequestInitializer() {
    @Override
    public void initialize(HttpRequest request) throws IOException {
      request.setHeaders(httpHeaders);
      request.setConnectTimeout(reportDownloadTimeout);
      request.setReadTimeout(reportDownloadTimeout);
      request.setThrowExceptionOnExecuteError(false);
      request.setLoggingEnabled(true);
      request.setResponseInterceptor(responseInterceptor);
    }
  });
}
项目:AkamaiOPEN-edgegrid-java    文件:GoogleHttpClientEdgeGridInterceptorTest.java   
@Test
public void testInterceptorWithHeader() throws URISyntaxException, IOException, RequestSigningException {
    HttpRequestFactory requestFactory = createSigningRequestFactory();

    URI uri = URI.create("https://endpoint.net/billing-usage/v1/reportSources");
    HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(uri));
    request.getHeaders().put("Host", "ignored-hostname.com");
    // Mimic what the library does to process the interceptor.
    request.getInterceptor().intercept(request);

    assertThat(request.getHeaders().containsKey("Host"), is(false));
    assertThat(request.getHeaders().containsKey("host"), is(true));
    assertThat((String) request.getHeaders().get("host"), equalTo("endpoint.net"));
    assertThat(request.getUrl().getHost(), equalTo("endpoint.net"));
    assertThat(request.getHeaders().getAuthorization(), not(isEmptyOrNullString()));
}
项目:google-cloud-datastore    文件:DatastoreFactoryTest.java   
/**
 * Specifying both credential and transport, the factory will use the
 * transport specified and not the one in the credential.
 */
@Test
public void makeClient_WithCredentialTransport() {
  NetHttpTransport credTransport = new NetHttpTransport();
  NetHttpTransport transport = new NetHttpTransport();
  GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(credTransport)
      .build();
  DatastoreOptions options = new DatastoreOptions.Builder()
      .projectId(PROJECT_ID)
      .credential(credential)
      .transport(transport)
      .build();
  HttpRequestFactory f = factory.makeClient(options);
  assertNotSame(credTransport, f.getTransport());
  assertEquals(transport, f.getTransport());
}
项目:generator-thundr-gae-react    文件:GoogleCloudStorageJsonApiClient.java   
public GoogleCloudStorageJsonApiClient(HttpRequestFactory httpRequestFactory,
    AppIdentityService appIdentityService,
    GoogleCredential gcsCredential) {
    this.httpRequestFactory = httpRequestFactory;
    this.appIdentityService = appIdentityService;
    this.gcsCredential = gcsCredential;
}
项目:java-monitoring-client-library    文件:GoogleJsonResponseExceptionHelper.java   
public static HttpResponse createHttpResponse(int statusCode, InputStream content)
    throws IOException {
  FakeHttpTransport transport = new FakeHttpTransport(statusCode, content);
  HttpRequestFactory factory = transport.createRequestFactory();
  HttpRequest request =
      factory.buildRequest(
          "foo", new GenericUrl("http://example.com/bar"), new EmptyHttpContent());
  request.setThrowExceptionOnExecuteError(false);
  return request.execute();
}
项目:ProjectAres    文件:HttpClient.java   
private HttpRequestFactory createRequestFactory() {
    return new NetHttpTransport().createRequestFactory(request -> {
        request.setConnectTimeout(HttpClient.this.config.getConnectTimeout());
        request.setReadTimeout(HttpClient.this.config.getReadTimeout());
        request.setNumberOfRetries(HttpClient.this.config.getRetries());
        request.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff.Builder().build()));
    });
}
项目:write_api_service    文件:GitHubBuilder.java   
/**
 * An annoying workaround to the issue that some github APi calls
 * are not exposed by egit library
 *
 * @param url
 * @return
 * @throws IOException
 */
private Map<String, Object> lowLevelGetRequest(String url) throws IOException {
    NetHttpTransport transport = new NetHttpTransport.Builder().build();
    HttpRequestFactory requestFactory = transport.createRequestFactory();
    HttpRequest httpRequest = requestFactory.buildGetRequest(new GenericUrl(url));
    HttpResponse execute = httpRequest.execute();
    InputStream content = execute.getContent();
    String s = IOUtils.toString(content, StandardCharsets.UTF_8);
    Gson gson = new Gson();
    Type stringStringMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    return gson.fromJson(s, stringStringMap);
}
项目:endpoints-management-java    文件:DefaultKeyUriSupplier.java   
/**
 * Constructor.
 *
 * @param httpRequestFactory is the factory used to make HTTP requests.
 * @param issuerKeyUrls is the configurations that map an issuer to the verification key URL.
 */
public DefaultKeyUriSupplier(
    HttpRequestFactory httpRequestFactory,
    Map<String, IssuerKeyUrlConfig> issuerKeyUrls) {
  Preconditions.checkNotNull(httpRequestFactory);
  Preconditions.checkNotNull(issuerKeyUrls);

  this.httpRequestFactory = httpRequestFactory;
  this.issuerKeyUrls = new ConcurrentHashMap<>(issuerKeyUrls);
}
项目:endpoints-management-java    文件:Authenticator.java   
@VisibleForTesting
static Authenticator create(Authentication authentication, Clock clock) {
  List<AuthProvider> providersList = authentication.getProvidersList();
  if (providersList == null || providersList.isEmpty()) {
    throw new IllegalArgumentException("No auth providers are defined in the config.");
  }
  Map<String, IssuerKeyUrlConfig> issuerKeyConfigs = generateIssuerKeyConfig(providersList);

  Map<String, String> issuersToProviderIds = Maps.newHashMap();
  for (AuthProvider authProvider : providersList) {
    issuersToProviderIds.put(authProvider.getIssuer(), authProvider.getId());
  }

  HttpRequestFactory httpRequestFactory = new NetHttpTransport().createRequestFactory();
  KeyUriSupplier defaultKeyUriSupplier =
      new DefaultKeyUriSupplier(httpRequestFactory, issuerKeyConfigs);
  JwksSupplier jwksSupplier = new DefaultJwksSupplier(httpRequestFactory, defaultKeyUriSupplier);
  JwksSupplier cachingJwksSupplier = new CachingJwksSupplier(jwksSupplier);
  AuthTokenVerifier authTokenVerifier = new DefaultAuthTokenVerifier(cachingJwksSupplier);
  AuthTokenDecoder authTokenDecoder = new DefaultAuthTokenDecoder(authTokenVerifier);
  AuthTokenDecoder cachingAuthTokenDecoder = new CachingAuthTokenDecoder(authTokenDecoder);

  return new Authenticator(
      cachingAuthTokenDecoder,
      clock,
      ImmutableMap.<String, String>copyOf(issuersToProviderIds));
}