當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpHeaders.setAuthorization方法代碼示例

本文整理匯總了Java中com.google.api.client.http.HttpHeaders.setAuthorization方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpHeaders.setAuthorization方法的具體用法?Java HttpHeaders.setAuthorization怎麽用?Java HttpHeaders.setAuthorization使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.google.api.client.http.HttpHeaders的用法示例。


在下文中一共展示了HttpHeaders.setAuthorization方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getUsersSince

import com.google.api.client.http.HttpHeaders; //導入方法依賴的package包/類
public List<User> getUsersSince(int since)
        throws IOException
{
    HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(API_ENDPOINT + "/users?since=" + since));

    HttpHeaders headers = new HttpHeaders();
    headers.setAuthorization("bearer " + tokenFactory.getToken());
    request.setHeaders(headers);

    HttpResponse response = executeWithRetry(request);
    // TODO: Handle error status code
    List<JsonObject> userObjects = Json.createReader(new StringReader(response.parseAsString())).readArray().getValuesAs(JsonObject.class);
    List<User> users = new ArrayList<>();
    for (JsonObject userObject : userObjects) {
        User user = new User(userObject.getInt("id"), userObject.getString("type"));
        user.setLogin(userObject.getString("login"));
        user.setAvatarUrl(userObject.getString("avatar_url"));
        users.add(user);
    }
    return users;
}
 
開發者ID:k0kubun,項目名稱:gitstar-ranking,代碼行數:22,代碼來源:GitHubClient.java

示例2: graphql

import com.google.api.client.http.HttpHeaders; //導入方法依賴的package包/類
private JsonObject graphql(String query)
        throws IOException
{
    String payload = Json.createObjectBuilder()
            .add("query", query)
            .add("variables", "{}")
            .build().toString();

    HttpRequest request = requestFactory.buildPostRequest(
            new GenericUrl(GRAPHQL_ENDPOINT),
            ByteArrayContent.fromString("application/json", payload));

    HttpHeaders headers = new HttpHeaders();
    headers.setAuthorization("bearer " + tokenFactory.getToken());
    request.setHeaders(headers);

    HttpResponse response = executeWithRetry(request);
    // TODO: Handle error status code
    JsonObject responseObject = Json.createReader(new StringReader(response.parseAsString())).readObject();
    if (responseObject.containsKey("errors")) {
        LOG.debug("errors with query:\n" + query);
        LOG.debug("response:\n" + responseObject.toString());
    }
    return responseObject;
}
 
開發者ID:k0kubun,項目名稱:gitstar-ranking,代碼行數:26,代碼來源:GitHubClient.java

示例3: testAuthorizationHeader

import com.google.api.client.http.HttpHeaders; //導入方法依賴的package包/類
@Test
public void testAuthorizationHeader() throws DnsimpleException, IOException {
  HttpHeaders headers = getDefaultHeaders();
  headers.setAuthorization("Bearer " + TEST_ACCESS_TOKEN);

  Client client = mockAndExpectClient("https://api.dnsimple.com/v2/accounts", HttpMethods.GET, headers, null, resource("listAccounts/success-account.http"));
  client.accounts.listAccounts();
}
 
開發者ID:dnsimple,項目名稱:dnsimple-java,代碼行數:9,代碼來源:ClientTest.java

示例4: createHeaders

import com.google.api.client.http.HttpHeaders; //導入方法依賴的package包/類
private HttpHeaders createHeaders(String merchantId, String userId, String authKey, String authMethod, String testbedToken) {
    HttpHeaders headers = new HttpHeaders();
    headers.set("X-Mcash-Merchant", merchantId);
    headers.set("X-Mcash-User", userId);
    headers.setAccept("application/vnd.mcash.api.merchant.v1+json");
    if (testbedToken != null) {
        headers.set("X-Testbed-Token", testbedToken);
    }
    if (authMethod.equals("SECRET")) {
        headers.setAuthorization(String.format("SECRET %s", authKey));
    } else {
        throw new IllegalArgumentException("Invalid auth method " + authMethod);
    }
    return headers;
}
 
開發者ID:fiLLLip,項目名稱:java-mapi-client,代碼行數:16,代碼來源:MCashClient.java

示例5: createHeaders

import com.google.api.client.http.HttpHeaders; //導入方法依賴的package包/類
/**
 * Creates the http headers object for this request, populated from data in
 * the session.
 * @throws AuthenticationException If OAuth authorization fails.
 */
private HttpHeaders createHeaders(String reportUrl, String version)
    throws AuthenticationException {
  HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.setAuthorization(
      authorizationHeaderProvider.getAuthorizationHeader(session, reportUrl));
  httpHeaders.setUserAgent(userAgentCombiner.getUserAgent(session.getUserAgent()));
  httpHeaders.set("developerToken", session.getDeveloperToken());
  httpHeaders.set("clientCustomerId", session.getClientCustomerId());
  ReportingConfiguration reportingConfiguration = session.getReportingConfiguration();
  if (reportingConfiguration != null) {
    reportingConfiguration.validate(version);
    if (reportingConfiguration.isSkipReportHeader() != null) {
      httpHeaders.set("skipReportHeader",
          Boolean.toString(reportingConfiguration.isSkipReportHeader()));
    }
    if (reportingConfiguration.isSkipColumnHeader() != null) {
      httpHeaders.set("skipColumnHeader",
          Boolean.toString(reportingConfiguration.isSkipColumnHeader()));
    }
    if (reportingConfiguration.isSkipReportSummary() != null) {
      httpHeaders.set("skipReportSummary",
          Boolean.toString(reportingConfiguration.isSkipReportSummary()));
    }
    if (reportingConfiguration.isIncludeZeroImpressions() != null) {
      httpHeaders.set(
          "includeZeroImpressions",
          Boolean.toString(reportingConfiguration.isIncludeZeroImpressions()));
    }
    if (reportingConfiguration.isUseRawEnumValues() != null) {
      httpHeaders.set(
          "useRawEnumValues",
          Boolean.toString(reportingConfiguration.isUseRawEnumValues()));
    }
  }
  return httpHeaders;
}
 
開發者ID:googleads,項目名稱:googleads-java-lib,代碼行數:42,代碼來源:ReportRequestFactoryHelper.java

示例6: getConfig

import com.google.api.client.http.HttpHeaders; //導入方法依賴的package包/類
/** Publish an event or state message using Cloud IoT Core via the HTTP API. */
public static void getConfig(String urlPath, String token, String projectId,
    String cloudRegion, String registryId, String deviceId, String version)
    throws UnsupportedEncodingException, IOException, JSONException, ProtocolException {
  // Build the resource path of the device that is going to be authenticated.
  String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryId, deviceId);
  urlPath = urlPath + devicePath + "/config?local_version=" + version;

  HttpRequestFactory requestFactory =
      HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest request) {
          request.setParser(new JsonObjectParser(JSON_FACTORY));
        }
      });

  final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
  HttpHeaders heads = new HttpHeaders();

  heads.setAuthorization(String.format("Bearer %s", token));
  heads.setContentType("application/json; charset=UTF-8");
  heads.setCacheControl("no-cache");

  req.setHeaders(heads);
  ExponentialBackOff backoff = new ExponentialBackOff.Builder()
      .setInitialIntervalMillis(500)
      .setMaxElapsedTimeMillis(900000)
      .setMaxIntervalMillis(6000)
      .setMultiplier(1.5)
      .setRandomizationFactor(0.5)
      .build();
  req.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
  HttpResponse res = req.execute();
  System.out.println(res.getStatusCode());
  System.out.println(res.getStatusMessage());
  InputStream in = res.getContent();

  System.out.println(CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8)));
}
 
開發者ID:GoogleCloudPlatform,項目名稱:java-docs-samples,代碼行數:43,代碼來源:HttpExample.java

示例7: publishMessage

import com.google.api.client.http.HttpHeaders; //導入方法依賴的package包/類
/** Publish an event or state message using Cloud IoT Core via the HTTP API. */
public static void publishMessage(String payload, String urlPath, String messageType,
    String token, String projectId, String cloudRegion, String registryId, String deviceId)
    throws UnsupportedEncodingException, IOException, JSONException, ProtocolException {
  // Build the resource path of the device that is going to be authenticated.
  String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryId, deviceId);
  String urlSuffix = messageType.equals("event") ? "publishEvent" : "setState";

  // Data sent through the wire has to be base64 encoded.
  Base64.Encoder encoder = Base64.getEncoder();

  String encPayload = encoder.encodeToString(payload.getBytes("UTF-8"));

  urlPath = urlPath + devicePath + ":" + urlSuffix;


  final HttpRequestFactory requestFactory =
      HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest request) {
          request.setParser(new JsonObjectParser(JSON_FACTORY));
        }
      });

  HttpHeaders heads = new HttpHeaders();
  heads.setAuthorization(String.format("Bearer %s", token));
  heads.setContentType("application/json; charset=UTF-8");
  heads.setCacheControl("no-cache");

  // Add post data. The data sent depends on whether we're updating state or publishing events.
  JSONObject data = new JSONObject();
  if (messageType.equals("event")) {
    data.put("binary_data", encPayload);
  } else {
    JSONObject state = new JSONObject();
    state.put("binary_data", encPayload);
    data.put("state", state);
  }

  ByteArrayContent content = new ByteArrayContent(
      "application/json", data.toString().getBytes("UTF-8"));

  final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
  req.setHeaders(heads);
  req.setContent(content);
  req.setRequestMethod("POST");
  ExponentialBackOff backoff = new ExponentialBackOff.Builder()
      .setInitialIntervalMillis(500)
      .setMaxElapsedTimeMillis(900000)
      .setMaxIntervalMillis(6000)
      .setMultiplier(1.5)
      .setRandomizationFactor(0.5)
      .build();
  req.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));

  HttpResponse res = req.execute();
  System.out.println(res.getStatusCode());
  System.out.println(res.getStatusMessage());
}
 
開發者ID:GoogleCloudPlatform,項目名稱:java-docs-samples,代碼行數:63,代碼來源:HttpExample.java


注:本文中的com.google.api.client.http.HttpHeaders.setAuthorization方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。