當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。