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

The following examples show how to use com.google.api.client.http.HttpHeaders#setContentType() . 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: 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 2
Source File: RestClient.java    From apigee-deploy-maven-plugin with Apache License 2.0 5 votes vote down vote up
public Long deleteBundle(Bundle bundle) throws IOException {
	Long deployedRevision = getDeployedRevision(bundle);

	if (deployedRevision == bundle.getRevision()) { // the same version is the active bundle deactivate first
		deactivateBundle(bundle);
	}

	GenericUrl url = new GenericUrl(format("%s/%s/organizations/%s/%s/%s/revisions/%d",
			profile.getHostUrl(),
			profile.getApi_version(),
			profile.getOrg(),
			bundle.getType().getPathName(),
			bundle.getName(),
			bundle.getRevision()));

	HttpHeaders headers = new HttpHeaders();
	headers.setAccept("application/json");
	headers.setContentType("application/octet-stream");
	HttpRequest deleteRestRequest = requestFactory.buildDeleteRequest(url);
	deleteRestRequest.setReadTimeout(0);
	deleteRestRequest.setHeaders(headers);

	HttpResponse response = null;
	response = executeAPI(profile, deleteRestRequest);

	//		String deleteResponse = response.parseAsString();
	AppConfig deleteResponse = response.parseAs(AppConfig.class);
	if (log.isInfoEnabled())
		log.info(PrintUtil.formatResponse(response, gson.toJson(deleteResponse).toString()));
	applyDelay();
	return deleteResponse.getRevision();
}
 
Example 3
Source File: HttpRequestContent.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(OutputStream out) throws IOException {
  Writer writer = new OutputStreamWriter(out, getCharset());
  // write method and URL
  writer.write(request.getRequestMethod());
  writer.write(" ");
  writer.write(request.getUrl().build());
  writer.write(" ");
  writer.write(HTTP_VERSION);
  writer.write(NEWLINE);

  // write headers
  HttpHeaders headers = new HttpHeaders();
  headers.fromHttpHeaders(request.getHeaders());
  headers.setAcceptEncoding(null).setUserAgent(null)
      .setContentEncoding(null).setContentType(null).setContentLength(null);
  // analyze the content
  HttpContent content = request.getContent();
  if (content != null) {
    headers.setContentType(content.getType());
    // NOTE: batch does not support gzip encoding
    long contentLength = content.getLength();
    if (contentLength != -1) {
      headers.setContentLength(contentLength);
    }
  }
  HttpHeaders.serializeHeadersForMultipartRequests(headers, null, null, writer);
  // HTTP headers are always terminated with an empty line; RFC 7230 ยง3
  writer.write(NEWLINE);
  writer.flush();
  // write content
  if (content != null) {
    content.writeTo(out);
  }
}
 
Example 4
Source File: IcannHttpReporter.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/** Uploads {@code reportBytes} to ICANN, returning whether or not it succeeded. */
public boolean send(byte[] reportBytes, String reportFilename) throws XmlException, IOException {
  validateReportFilename(reportFilename);
  GenericUrl uploadUrl = new GenericUrl(makeUrl(reportFilename));
  HttpRequest request =
      httpTransport
          .createRequestFactory()
          .buildPutRequest(uploadUrl, new ByteArrayContent(CSV_UTF_8.toString(), reportBytes));

  HttpHeaders headers = request.getHeaders();
  headers.setBasicAuthentication(getTld(reportFilename) + "_ry", password);
  headers.setContentType(CSV_UTF_8.toString());
  request.setHeaders(headers);
  request.setFollowRedirects(false);

  HttpResponse response = null;
  logger.atInfo().log(
      "Sending report to %s with content length %d", uploadUrl, request.getContent().getLength());
  boolean success = true;
  try {
    response = request.execute();
    byte[] content;
    try {
      content = ByteStreams.toByteArray(response.getContent());
    } finally {
      response.getContent().close();
    }
    logger.atInfo().log(
        "Received response code %d with content %s",
        response.getStatusCode(), new String(content, UTF_8));
    XjcIirdeaResult result = parseResult(content);
    if (result.getCode().getValue() != 1000) {
      success = false;
      logger.atWarning().log(
          "PUT rejected, status code %s:\n%s\n%s",
          result.getCode(), result.getMsg(), result.getDescription());
    }
  } finally {
    if (response != null) {
      response.disconnect();
    } else {
      success = false;
      logger.atWarning().log("Received null response from ICANN server at %s", uploadUrl);
    }
  }
  return success;
}
 
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());
}
 
Example 7
Source File: MultipartFormDataContent.java    From Broadsheet.ie-Android with MIT License 4 votes vote down vote up
@Override
public void writeTo(OutputStream out) throws IOException {

    Writer writer = new OutputStreamWriter(out, getCharset());
    String boundary = getBoundary();

    for (Part part : parts) {
        HttpHeaders headers = new HttpHeaders().setAcceptEncoding(null);
        if (part.headers != null) {
            headers.fromHttpHeaders(part.headers);
        }
        headers.setContentEncoding(null).setUserAgent(null).setContentType(null).setContentLength(null);
        // analyze the content
        HttpContent content = part.content;
        StreamingContent streamingContent = null;
        String contentDisposition = String.format("form-data; name=\"%s\"", part.name);
        if (part.filename != null) {
            headers.setContentType(content.getType());
            contentDisposition += String.format("; filename=\"%s\"", part.filename);
        }
        headers.set("Content-Disposition", contentDisposition);
        HttpEncoding encoding = part.encoding;
        if (encoding == null) {
            streamingContent = content;
        } else {
            headers.setContentEncoding(encoding.getName());
            streamingContent = new HttpEncodingStreamingContent(content, encoding);
        }
        // write separator
        writer.write(TWO_DASHES);
        writer.write(boundary);
        writer.write(NEWLINE);
        // write headers
        HttpHeaders.serializeHeadersForMultipartRequests(headers, null, null, writer);
        // write content
        if (streamingContent != null) {
            writer.write(NEWLINE);
            writer.flush();
            streamingContent.writeTo(out);
            writer.write(NEWLINE);
        }
    }
    // write end separator
    writer.write(TWO_DASHES);
    writer.write(boundary);
    writer.write(TWO_DASHES);
    writer.write(NEWLINE);
    writer.flush();
}
 
Example 8
Source File: BatchJobUploader.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
private HttpHeaders createHttpHeaders() {
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType("application/xml");
  headers.setUserAgent(session.getUserAgent());
  return headers;
}