当前位置: 首页>>代码示例>>Java>>正文


Java NetHttpTransport类代码示例

本文整理汇总了Java中com.google.api.client.http.javanet.NetHttpTransport的典型用法代码示例。如果您正苦于以下问题:Java NetHttpTransport类的具体用法?Java NetHttpTransport怎么用?Java NetHttpTransport使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


NetHttpTransport类属于com.google.api.client.http.javanet包,在下文中一共展示了NetHttpTransport类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getPublicKeysJson

import com.google.api.client.http.javanet.NetHttpTransport; //导入依赖的package包/类
/**
 *
 * @return
 * @throws IOException
 */
private JsonObject getPublicKeysJson() throws IOException {
    // get public keys
    URI uri = URI.create(pubKeyUrl);
    GenericUrl url = new GenericUrl(uri);
    HttpTransport http = new NetHttpTransport();
    HttpResponse response = http.createRequestFactory().buildGetRequest(url).execute();

    // store json from request
    String json = response.parseAsString();
    // disconnect
    response.disconnect();

    // parse json to object
    JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();

    return jsonObject;
}
 
开发者ID:rvep,项目名称:dev_backend,代码行数:23,代码来源:FirebaseAuthVerifier.java

示例2: BigQueryExporter

import com.google.api.client.http.javanet.NetHttpTransport; //导入依赖的package包/类
public BigQueryExporter(BigQueryExporterConfiguration config) {
	this.config = config;
	this.checkedSchemas = new HashSet<String>();
	this.existingSchemaMap = new HashMap<String, com.google.api.services.bigquery.model.TableSchema>();

	HttpTransport transport = new NetHttpTransport();
	JsonFactory jsonFactory = new JacksonFactory();
	GoogleCredential credential;
	try {
		credential = GoogleCredential.getApplicationDefault(transport,
				jsonFactory);
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
	if (credential.createScopedRequired()) {
		credential = credential.createScoped(BigqueryScopes.all());
	}
	this.bq = new Bigquery.Builder(transport, jsonFactory, credential)
			.setApplicationName(this.config.applicationName).build();
}
 
开发者ID:frew,项目名称:chute,代码行数:21,代码来源:BigQueryExporter.java

示例3: createAuthorizedClient

import com.google.api.client.http.javanet.NetHttpTransport; //导入依赖的package包/类
/**
 * Creates an authorized CloudKMS client service using Application Default Credentials.
 *
 * @return an authorized CloudKMS client
 * @throws IOException if there's an error getting the default credentials.
 */
public static CloudKMS createAuthorizedClient() throws IOException {
  // Create the credential
  HttpTransport transport = new NetHttpTransport();
  JsonFactory jsonFactory = new JacksonFactory();
  // Authorize the client using Application Default Credentials
  // @see https://g.co/dv/identity/protocols/application-default-credentials
  GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);

  // Depending on the environment that provides the default credentials (e.g. Compute Engine, App
  // Engine), the credentials may require us to specify the scopes we need explicitly.
  // Check for this case, and inject the scope if required.
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(CloudKMSScopes.all());
  }

  return new CloudKMS.Builder(transport, jsonFactory, credential)
      .setApplicationName("CloudKMS snippets")
      .build();
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:26,代码来源:Snippets.java

示例4: authorize

import com.google.api.client.http.javanet.NetHttpTransport; //导入依赖的package包/类
private static void authorize(DataStoreFactory storeFactory, String userId) throws Exception {
  // Depending on your application, there may be more appropriate ways of
  // performing the authorization flow (such as on a servlet), see
  // https://developers.google.com/api-client-library/java/google-api-java-client/oauth2#authorization_code_flow
  // for more information.
  GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
      new NetHttpTransport(),
      new JacksonFactory(),
      CLIENT_ID,
      CLIENT_SECRET,
      Arrays.asList(SCOPE))
      .setDataStoreFactory(storeFactory)
      // Set the access type to offline so that the token can be refreshed.
      // By default, the library will automatically refresh tokens when it
      // can, but this can be turned off by setting
      // api.dfp.refreshOAuth2Token=false in your ads.properties file.
      .setAccessType("offline").build();

  String authorizeUrl =
      authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();
  System.out.printf("Paste this url in your browser:%n%s%n", authorizeUrl);

  // Wait for the authorization code.
  System.out.println("Type the code you received here: ");
  @SuppressWarnings("DefaultCharset") // Reading from stdin, so default charset is appropriate.
  String authorizationCode = new BufferedReader(new InputStreamReader(System.in)).readLine();

  // Authorize the OAuth2 token.
  GoogleAuthorizationCodeTokenRequest tokenRequest =
      authorizationFlow.newTokenRequest(authorizationCode);
  tokenRequest.setRedirectUri(CALLBACK_URL);
  GoogleTokenResponse tokenResponse = tokenRequest.execute();

  // Store the credential for the user.
  authorizationFlow.createAndStoreCredential(tokenResponse, userId);
}
 
开发者ID:googleads,项目名称:googleads-java-lib,代码行数:37,代码来源:AdvancedCreateCredentialFromScratch.java

示例5: getTubeService

import com.google.api.client.http.javanet.NetHttpTransport; //导入依赖的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

示例6: YouTubeSingleton

import com.google.api.client.http.javanet.NetHttpTransport; //导入依赖的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

示例7: init

import com.google.api.client.http.javanet.NetHttpTransport; //导入依赖的package包/类
private void init() {
    NetHttpTransport.Builder netBuilder = new NetHttpTransport.Builder();
    Proxy proxy = ProxyManager.getProxyIf();
    if (proxy != null) {
        netBuilder.setProxy(proxy);
    }
    this.customsearch = new Customsearch(netBuilder.build(), new JacksonFactory(), httpRequest -> {
    });
}
 
开发者ID:oxaoo,项目名称:mingi,代码行数:10,代码来源:WebSearchFinder.java

示例8: YouTubeSingleton

import com.google.api.client.http.javanet.NetHttpTransport; //导入依赖的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

示例9: YoutubeSearcher

import com.google.api.client.http.javanet.NetHttpTransport; //导入依赖的package包/类
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)");
    }
}
 
开发者ID:jagrosh,项目名称:Spectra,代码行数:19,代码来源:YoutubeSearcher.java

示例10: get

import com.google.api.client.http.javanet.NetHttpTransport; //导入依赖的package包/类
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();
    }
}
 
开发者ID:Fewlaps,项目名称:http-monitor,代码行数:19,代码来源:HttpClient.java

示例11: newManager

import com.google.api.client.http.javanet.NetHttpTransport; //导入依赖的package包/类
/**
 * Interface for requesting new connections to the {@link DeploymentManager} service.
 *
 * @param credentials The credentials to use to authenticate with the service
 * @return a new instance of the {@link DeploymentManager} service for issuing requests
 * @throws CloudManagementException if a service connection cannot be established.
 */
public DeploymentManager newManager(GoogleRobotCredentials credentials)
    throws CloudManagementException {
  try {
    DeploymentManager.Builder builder = new DeploymentManager.Builder(new NetHttpTransport(),
        new JacksonFactory(), requireNonNull(credentials).getGoogleCredential(getRequirement()));

    // The descriptor surfaces global overrides for the API being used
    // for cloud management.
    AbstractCloudDeploymentDescriptor descriptor = getDescriptor();

    return builder.setApplicationName(Messages.CloudDeploymentModule_AppName())
        .setRootUrl(descriptor.getRootUrl()).setServicePath(descriptor.getServicePath()).build();
  } catch (GeneralSecurityException e) {
    throw new CloudManagementException(Messages.CloudDeploymentModule_ConnectionError(), e);
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:jenkins-deployment-manager-plugin,代码行数:24,代码来源:CloudDeploymentModule.java

示例12: generateCredentials

import com.google.api.client.http.javanet.NetHttpTransport; //导入依赖的package包/类
public GoogleCredential generateCredentials(){
    GoogleCredential credential = null;
    try {
        File p12 = new File(this.getClass().getResource("/" + p12FilePath).getFile());
        if (!p12.exists()) {
            p12 = new File(p12FilePath);
        }
        credential = new GoogleCredential.Builder()
                .setTransport(new NetHttpTransport())
                .setJsonFactory(new JacksonFactory())
                .setServiceAccountId(serviceAccountId)
                .setServiceAccountScopes(asList(scopes.split(";")))
                .setServiceAccountPrivateKeyFromP12File(p12)
                .build();
    } catch (GeneralSecurityException | IOException e) {
        String message = "Cannot generate google credentials for connection.";
        logger.error(message, e);
    }
    return credential;
}
 
开发者ID:JujaLabs,项目名称:microservices,代码行数:21,代码来源:SpreadsheetServiceProvider.java

示例13: createGoogleCredential

import com.google.api.client.http.javanet.NetHttpTransport; //导入依赖的package包/类
private static void createGoogleCredential() throws GeneralSecurityException, IOException {

        if (SERVICE_ACCOUNT_EMAIL == null) {
            SERVICE_ACCOUNT_EMAIL = PropertiesUtils.getProperties("google.service_account_email");
        }

        if (SERVICE_ACCOUNT_PKCS12_FILE == null) {
            openFile();
        }

        if (CREDENTIAL == null) {
            HttpTransport httpTransport = new NetHttpTransport();
            JacksonFactory jsonFactory = new JacksonFactory();

            String[] SCOPESArray = {"https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/gmail.compose"};
            CREDENTIAL = new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountScopes(getScopes())
                .setServiceAccountPrivateKeyFromP12File(SERVICE_ACCOUNT_PKCS12_FILE)
                .build();
        } else {
            refreshToken();
        }
    }
 
开发者ID:oncokb,项目名称:oncokb,代码行数:27,代码来源:GoogleAuth.java

示例14: load

import com.google.api.client.http.javanet.NetHttpTransport; //导入依赖的package包/类
public Optional<Credential> load() {
     Properties properties = new Properties();
     try {
File file = getAuthenticationFile(options);
         if(!file.exists() || !file.canRead()) {
             LOGGER.log(Level.FINE, "Cannot find or read properties file. Returning empty credentials.");
             return Optional.empty();
         }
         properties.load(new FileReader(file));
         HttpTransport httpTransport = new NetHttpTransport();
         JsonFactory jsonFactory = new JacksonFactory();
         GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory)
                 .setTransport(httpTransport).setClientSecrets(OAuth2ClientCredentials.CLIENT_ID, OAuth2ClientCredentials.CLIENT_SECRET).build();
         credential.setAccessToken(properties.getProperty(PROP_ACCESS_TOKEN));
         credential.setRefreshToken(properties.getProperty(PROP_REFRESH_TOKEN));
         return Optional.of(credential);
     } catch (IOException e) {
         throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to load properties file: " + e.getMessage(), e);
     }
 }
 
开发者ID:siom79,项目名称:jdrivesync,代码行数:21,代码来源:CredentialStore.java

示例15: testBrokenPipe_NetHttpTransport

import com.google.api.client.http.javanet.NetHttpTransport; //导入依赖的package包/类
@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"));
    }
}
 
开发者ID:morimekta,项目名称:providence,代码行数:19,代码来源:HttpClientHandlerNetworkTest.java


注:本文中的com.google.api.client.http.javanet.NetHttpTransport类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。