本文整理匯總了Java中com.google.api.client.http.HttpTransport類的典型用法代碼示例。如果您正苦於以下問題:Java HttpTransport類的具體用法?Java HttpTransport怎麽用?Java HttpTransport使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
HttpTransport類屬於com.google.api.client.http包,在下文中一共展示了HttpTransport類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: getClient
import com.google.api.client.http.HttpTransport; //導入依賴的package包/類
/** Builds a new Pubsub client and returns it. */
public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory)
throws IOException {
checkNotNull(httpTransport);
checkNotNull(jsonFactory);
GoogleCredential credential =
GoogleCredential.getApplicationDefault(httpTransport, jsonFactory);
if (credential.createScopedRequired()) {
credential = credential.createScoped(PubsubScopes.all());
}
if (credential.getClientAuthentication() != null) {
System.out.println(
"\n***Warning! You are not using service account credentials to "
+ "authenticate.\nYou need to use service account credentials for this example,"
+ "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run "
+ "out of PubSub quota very quickly.\nSee "
+ "https://developers.google.com/identity/protocols/application-default-credentials.");
System.exit(1);
}
HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
return new Pubsub.Builder(httpTransport, jsonFactory, initializer)
.setApplicationName(APP_NAME)
.build();
}
示例2: performRequest
import com.google.api.client.http.HttpTransport; //導入依賴的package包/類
private static void performRequest(String accessToken, String refreshToken, String apiKey, String apiSecret) throws GeneralSecurityException, IOException, MessagingException {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = new JacksonFactory();
final Credential credential = convertToGoogleCredential(accessToken, refreshToken, apiSecret, apiKey);
Builder builder = new Gmail.Builder(httpTransport, jsonFactory, credential);
builder.setApplicationName("OAuth API Sample");
Gmail gmail = builder.build();
MimeMessage content = createEmail("[email protected]", "[email protected]", "Test Email", "It works");
Message message = createMessageWithEmail(content);
gmail.users().messages().send("[email protected]", message).execute();
}
示例3: createRefreshTokenCredential
import com.google.api.client.http.HttpTransport; //導入依賴的package包/類
private static GoogleCredentials createRefreshTokenCredential() throws IOException {
final MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addClient(CLIENT_ID, CLIENT_SECRET);
transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN);
Map<String, Object> secretJson = new HashMap<>();
secretJson.put("client_id", CLIENT_ID);
secretJson.put("client_secret", CLIENT_SECRET);
secretJson.put("refresh_token", REFRESH_TOKEN);
secretJson.put("type", "authorized_user");
InputStream refreshTokenStream =
new ByteArrayInputStream(JSON_FACTORY.toByteArray(secretJson));
return UserCredentials.fromStream(refreshTokenStream, new HttpTransportFactory() {
@Override
public HttpTransport create() {
return transport;
}
});
}
示例4: createClient
import com.google.api.client.http.HttpTransport; //導入依賴的package包/類
/**
* Setup authorization for local app based on private key.
* See <a href="https://cloud.google.com/pubsub/configure">cloud.google.com/pubsub/configure</a>
*/
private void createClient(String private_key_file, String email) throws IOException, GeneralSecurityException {
HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(transport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountScopes(PubsubScopes.all())
.setServiceAccountId(email)
.setServiceAccountPrivateKeyFromP12File(new File(private_key_file))
.build();
// Please use custom HttpRequestInitializer for automatic retry upon failures.
// HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
pubsub = new Pubsub.Builder(transport, JSON_FACTORY, credential)
.setApplicationName("eaipubsub")
.build();
}
示例5: createApplicationDefaultCredential
import com.google.api.client.http.HttpTransport; //導入依賴的package包/類
private static GoogleCredentials createApplicationDefaultCredential() throws IOException {
final MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN);
// Set the GOOGLE_APPLICATION_CREDENTIALS environment variable for application-default
// credentials. This requires us to write the credentials to the location specified by the
// environment variable.
File credentialsFile = File.createTempFile("google-test-credentials", "json");
PrintWriter writer = new PrintWriter(Files.newBufferedWriter(credentialsFile.toPath(), UTF_8));
writer.print(ServiceAccount.EDITOR.asString());
writer.close();
Map<String, String> environmentVariables =
ImmutableMap.<String, String>builder()
.put("GOOGLE_APPLICATION_CREDENTIALS", credentialsFile.getAbsolutePath())
.build();
TestUtils.setEnvironmentVariables(environmentVariables);
credentialsFile.deleteOnExit();
return GoogleCredentials.getApplicationDefault(new HttpTransportFactory() {
@Override
public HttpTransport create() {
return transport;
}
});
}
示例6: getApplicationDefaultCredentials
import com.google.api.client.http.HttpTransport; //導入依賴的package包/類
/**
* Ensures initialization of Google Application Default Credentials. Any test that depends on
* ADC should consider this as a fixture, and invoke it before hand. Since ADC are initialized
* once per JVM, this makes sure that all dependent tests get the same ADC instance, and
* can reliably reason about the tokens minted using it.
*/
public static synchronized GoogleCredentials getApplicationDefaultCredentials()
throws IOException {
if (defaultCredentials != null) {
return defaultCredentials;
}
final MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), TEST_ADC_ACCESS_TOKEN);
File serviceAccount = new File("src/test/resources/service_accounts", "editor.json");
Map<String, String> environmentVariables =
ImmutableMap.<String, String>builder()
.put("GOOGLE_APPLICATION_CREDENTIALS", serviceAccount.getAbsolutePath())
.build();
setEnvironmentVariables(environmentVariables);
defaultCredentials = GoogleCredentials.getApplicationDefault(new HttpTransportFactory() {
@Override
public HttpTransport create() {
return transport;
}
});
return defaultCredentials;
}
示例7: configureMock
import com.google.api.client.http.HttpTransport; //導入依賴的package包/類
protected static HttpTransport configureMock() {
return new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, final String url) throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
response.setStatusCode(200);
response.setContentType(Json.MEDIA_TYPE);
if (url.startsWith(GCE_METADATA_URL)) {
logger.info("--> Simulate GCE Auth/Metadata response for [{}]", url);
response.setContent(readGoogleInternalJsonResponse(url));
} else {
logger.info("--> Simulate GCE API response for [{}]", url);
response.setContent(readGoogleApiJsonResponse(url));
}
return response;
}
};
}
};
}
示例8: getClient
import com.google.api.client.http.HttpTransport; //導入依賴的package包/類
/**
* Builds a new Pubsub client and returns it.
*/
public static Pubsub getClient(final HttpTransport httpTransport,
final JsonFactory jsonFactory)
throws IOException {
checkNotNull(httpTransport);
checkNotNull(jsonFactory);
GoogleCredential credential =
GoogleCredential.getApplicationDefault(httpTransport, jsonFactory);
if (credential.createScopedRequired()) {
credential = credential.createScoped(PubsubScopes.all());
}
if (credential.getClientAuthentication() != null) {
System.out.println("\n***Warning! You are not using service account credentials to "
+ "authenticate.\nYou need to use service account credentials for this example,"
+ "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run "
+ "out of PubSub quota very quickly.\nSee "
+ "https://developers.google.com/identity/protocols/application-default-credentials.");
System.exit(1);
}
HttpRequestInitializer initializer =
new RetryHttpInitializerWrapper(credential);
return new Pubsub.Builder(httpTransport, jsonFactory, initializer)
.setApplicationName(APP_NAME)
.build();
}
示例9: getProjectsApiStub
import com.google.api.client.http.HttpTransport; //導入依賴的package包/類
/**
* Return the Projects api object used for accessing the Cloud Resource Manager Projects API.
* @return Projects api object used for accessing the Cloud Resource Manager Projects API
* @throws GeneralSecurityException Thrown if there's a permissions error.
* @throws IOException Thrown if there's an IO error initializing the API object.
*/
public static synchronized Projects getProjectsApiStub()
throws GeneralSecurityException, IOException {
if (projectApiStub != null) {
return projectApiStub;
}
HttpTransport transport;
GoogleCredential credential;
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
transport = GoogleNetHttpTransport.newTrustedTransport();
credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
if (credential.createScopedRequired()) {
Collection<String> scopes = CloudResourceManagerScopes.all();
credential = credential.createScoped(scopes);
}
projectApiStub = new CloudResourceManager
.Builder(transport, jsonFactory, credential)
.build()
.projects();
return projectApiStub;
}
示例10: getServiceAccountsApiStub
import com.google.api.client.http.HttpTransport; //導入依賴的package包/類
/**
* Get the API stub for accessing the IAM Service Accounts API.
* @return ServiceAccounts api stub for accessing the IAM Service Accounts API.
* @throws IOException Thrown if there's an IO error initializing the api connection.
* @throws GeneralSecurityException Thrown if there's a security error
* initializing the connection.
*/
public static ServiceAccounts getServiceAccountsApiStub() throws IOException, GeneralSecurityException {
if (serviceAccountsApiStub == null) {
HttpTransport transport;
GoogleCredential credential;
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
transport = GoogleNetHttpTransport.newTrustedTransport();
credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
if (credential.createScopedRequired()) {
Collection<String> scopes = IamScopes.all();
credential = credential.createScoped(scopes);
}
serviceAccountsApiStub = new Iam.Builder(transport, jsonFactory, credential)
.build()
.projects()
.serviceAccounts();
}
return serviceAccountsApiStub;
}
示例11: ServiceConfigSupplier
import com.google.api.client.http.HttpTransport; //導入依賴的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();
}
示例12: getPlatformFromEnvironment
import com.google.api.client.http.HttpTransport; //導入依賴的package包/類
@VisibleForTesting
static ReportedPlatforms getPlatformFromEnvironment(
Map<String, String> env, Properties properties, HttpTransport transport) {
if (env.containsKey("KUBERNETES_SERVICE_HOST")) {
return ReportedPlatforms.GKE;
}
boolean hasMetadataServer = hasMetadataServer(transport);
String gaeEnvironment = properties.getProperty("com.google.appengine.runtime.environment");
boolean onGae = gaeEnvironment != null && gaeEnvironment.startsWith("Production");
if (hasMetadataServer && env.containsKey("GAE_SERVICE")) {
return ReportedPlatforms.GAE_FLEX;
} else if (hasMetadataServer) {
return ReportedPlatforms.GCE;
} else if (onGae) {
return ReportedPlatforms.GAE_STANDARD;
}
if (gaeEnvironment != null && gaeEnvironment.startsWith("Development")) {
return ReportedPlatforms.DEVELOPMENT;
}
return ReportedPlatforms.UNKNOWN;
}
示例13: testSupplyJwksFromX509Certificate
import com.google.api.client.http.HttpTransport; //導入依賴的package包/類
@Test
public void testSupplyJwksFromX509Certificate() throws
NoSuchAlgorithmException, JsonProcessingException {
RsaJsonWebKey rsaJsonWebKey = TestUtils.generateRsaJsonWebKey("key-id");
String cert = TestUtils.generateX509Cert(rsaJsonWebKey);
String keyId = "key-id";
String json = OBJECT_WRITER.writeValueAsString(ImmutableMap.of(keyId, cert));
HttpTransport httpTransport = new TestingHttpTransport(json, null);
DefaultJwksSupplier jwksSupplier =
new DefaultJwksSupplier(httpTransport.createRequestFactory(), keyUriSupplier);
JsonWebKeySet jsonWebKeySet = jwksSupplier.supply(ISSUER);
JsonWebKey jsonWebKey = Iterables.getOnlyElement(jsonWebKeySet.getJsonWebKeys());
assertEquals(keyId, jsonWebKey.getKeyId());
assertKeysEqual(rsaJsonWebKey.getPublicKey(), jsonWebKey.getKey());
}
示例14: before
import com.google.api.client.http.HttpTransport; //導入依賴的package包/類
@Before
public void before() throws Exception {
when(subfactory.create(
anyString(),
any(HttpTransport.class),
any(JsonFactory.class),
any(HttpRequestInitializer.class)))
.thenReturn(bigquery);
when(bigquery.datasets()).thenReturn(bigqueryDatasets);
when(bigqueryDatasets.insert(eq("Project-Id"), any(Dataset.class)))
.thenReturn(bigqueryDatasetsInsert);
when(bigquery.tables()).thenReturn(bigqueryTables);
when(bigqueryTables.insert(eq("Project-Id"), any(String.class), any(Table.class)))
.thenReturn(bigqueryTablesInsert);
factory = new BigqueryFactory();
factory.subfactory = subfactory;
factory.bigquerySchemas =
new ImmutableMap.Builder<String, ImmutableList<TableFieldSchema>>()
.put(
"Table-Id",
ImmutableList.of(new TableFieldSchema().setName("column1").setType(STRING.name())))
.put(
"Table2",
ImmutableList.of(new TableFieldSchema().setName("column1").setType(STRING.name())))
.build();
}
示例15: build
import com.google.api.client.http.HttpTransport; //導入依賴的package包/類
@Override
public DataprocHadoopRunner build() {
CredentialProvider credentialProvider = Optional.ofNullable(this.credentialProvider)
.orElseGet(DefaultCredentialProvider::new);
try {
final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
final JsonFactory jsonFactory = new JacksonFactory();
final GoogleCredential credentials = credentialProvider.getCredential(SCOPES);
final Dataproc dataproc = new Dataproc.Builder(httpTransport, jsonFactory, credentials)
.setApplicationName(APPLICATION_NAME).build();
final Storage storage = new Storage.Builder(httpTransport, jsonFactory, credentials)
.setApplicationName(APPLICATION_NAME).build();
final DataprocClient dataprocClient =
new DataprocClient(dataproc, storage, projectId, clusterId, clusterProperties);
return new DataprocHadoopRunnerImpl(dataprocClient);
} catch (Throwable e) {
throw Throwables.propagate(e);
}
}