Java Code Examples for com.google.api.client.http.HttpHeaders#setAuthorization()

The following examples show how to use com.google.api.client.http.HttpHeaders#setAuthorization() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MastodonHttpUtilities.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
/** Posts a new status for the user, initially marked as private.**/
public void postStatus(String content, String idempotencyKey) throws IOException {
  ImmutableMap<String, String> formParams = ImmutableMap.of(
      "status", content,
      // Default everything to private to avoid a privacy incident
      "visibility", "private"
  );
  UrlEncodedContent urlEncodedContent = new UrlEncodedContent(formParams);
  HttpRequest postRequest = TRANSPORT.createRequestFactory()
      .buildPostRequest(
          new GenericUrl(baseUrl + POST_URL),
          urlEncodedContent)
      .setThrowExceptionOnExecuteError(false);
  HttpHeaders headers = new HttpHeaders();
  headers.setAuthorization("Bearer " + accessToken);
  if (!Strings.isNullOrEmpty(idempotencyKey)) {
    // This prevents the same post from being posted twice in the case of network errors
    headers.set("Idempotency-Key", idempotencyKey);
  }
  postRequest.setHeaders(headers);

  HttpResponse response = postRequest.execute();

  validateResponse(postRequest, response, 200);
}
 
Example 2
Source File: MastodonHttpUtilities.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
private String requestRaw(String path) throws IOException {
  HttpRequest getRequest = TRANSPORT.createRequestFactory().buildGetRequest(
      new GenericUrl(baseUrl + path));
  HttpHeaders headers = new HttpHeaders();
  headers.setAuthorization("Bearer " + accessToken);
  getRequest.setHeaders(headers);

  HttpResponse response = getRequest.execute();

  validateResponse(getRequest, response, 200);
  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

  IOUtils.copy(response.getContent(), byteArrayOutputStream, true);
  return byteArrayOutputStream.toString();
}
 
Example 3
Source File: GoogleVideosInterface.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
<T> T makePostRequest(
    String url, Optional<Map<String, String>> parameters, HttpContent httpContent, Class<T> clazz)
    throws IOException {
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
  HttpRequest postRequest =
      requestFactory.buildPostRequest(
          new GenericUrl(url + "?" + generateParamsString(parameters)), httpContent);

  // TODO: Figure out why this is necessary for videos but not for photos
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType("application/octet-stream");
  headers.setAuthorization("Bearer " + this.credential.getAccessToken());
  headers.set("X-Goog-Upload-Protocol", "raw");
  postRequest.setHeaders(headers);

  HttpResponse response = postRequest.execute();
  int statusCode = response.getStatusCode();
  if (statusCode != 200) {
    throw new IOException(
        "Bad status code: " + statusCode + " error: " + response.getStatusMessage());
  }
  String result =
      CharStreams.toString(new InputStreamReader(response.getContent(), Charsets.UTF_8));
  if (clazz.isAssignableFrom(String.class)) {
    return (T) result;
  } else {
    return objectMapper.readValue(result, clazz);
  }
}
 
Example 4
Source File: ReportRequestFactoryHelper.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 5
Source File: HttpExample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/** Publish an event or state message using Cloud IoT Core via the HTTP API. */
protected static void getConfig(
    String urlPath,
    String token,
    String projectId,
    String cloudRegion,
    String registryId,
    String deviceId,
    String version)
    throws IOException {
  // 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.name())));
}
 
Example 6
Source File: HttpExample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/** Publish an event or state message using Cloud IoT Core via the HTTP API. */
protected static void publishMessage(
    String payload,
    String urlPath,
    String messageType,
    String token,
    String projectId,
    String cloudRegion,
    String registryId,
    String deviceId)
    throws IOException, JSONException {
  // 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 = "event".equals(messageType) ? "publishEvent" : "setState";

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

  String encPayload = encoder.encodeToString(payload.getBytes(StandardCharsets.UTF_8.name()));

  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 ("event".equals(messageType)) {
    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(StandardCharsets.UTF_8.name()));

  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());
}