Java Code Examples for com.google.api.client.http.HttpResponse#getHeaders()

The following examples show how to use com.google.api.client.http.HttpResponse#getHeaders() . 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: SslHelper.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private String makeCall(HttpTransport transport) throws IOException {
  HttpRequest get =
      transport.createRequestFactory()
          .buildPostRequest(new GenericUrl(INRPUT_LOGIN_SERVER), null)
          .setFollowRedirects(false)
          .setThrowExceptionOnExecuteError(false);

  HttpResponse response = get.execute();
  if (response.getStatusCode() != 302) {
    throw new IOException("Unexpected return code: "
        + response.getStatusCode()
        + "\nMessage:\n"
        + response.getStatusMessage());
  }
  String cookieValue = response.getHeaders().getFirstHeaderStringValue("set-cookie");
  if (Strings.isNullOrEmpty(cookieValue)) {
    throw new IOException("Couldn't extract cookie value from headers: " + response.getHeaders());
  }
  return cookieValue;
}
 
Example 2
Source File: GoogleHttpClient.java    From feign with Apache License 2.0 6 votes vote down vote up
private final Response convertResponse(final Request inputRequest,
                                       final HttpResponse inputResponse)
    throws IOException {
  final HttpHeaders headers = inputResponse.getHeaders();
  Integer contentLength = null;
  if (headers.getContentLength() != null && headers.getContentLength() <= Integer.MAX_VALUE) {
    contentLength = inputResponse.getHeaders().getContentLength().intValue();
  }
  return Response.builder()
      .body(inputResponse.getContent(), contentLength)
      .status(inputResponse.getStatusCode())
      .reason(inputResponse.getStatusMessage())
      .headers(toMap(inputResponse.getHeaders()))
      .request(inputRequest)
      .build();
}
 
Example 3
Source File: SolidUtilities.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
private static void validateResponse(HttpResponse response, int expectedCode) throws IOException {
  if (response.getStatusCode() != expectedCode) {
    throw new IOException("Unexpected return code: "
        + response.getStatusCode()
        + "\nMessage:\n"
        + response.getStatusMessage()
        + "\nHeaders:\n"
        + response.getHeaders());

  }
}
 
Example 4
Source File: MastodonHttpUtilities.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
private static void validateResponse(
    HttpRequest request, HttpResponse response, int expectedCode) throws IOException {
  if (response.getStatusCode() != expectedCode) {
    throw new IOException("Unexpected return code: "
        + response.getStatusCode()
        + "\nMessage:\n"
        + response.getStatusMessage()
        + "\nfrom:\n"
        + request.getUrl()
        + "\nHeaders:\n"
        + response.getHeaders());
  }
}
 
Example 5
Source File: GitHubApiTransportImpl.java    From copybara with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Nullable
private static String maybeGetLinkHeader(HttpResponse response) {
  HttpHeaders headers = response.getHeaders();
  List<String> link = (List<String>) headers.get("Link");
  if (link == null) {
    return null;
  }
  return Iterables.getOnlyElement(link);
}
 
Example 6
Source File: RetryHttpInitializer.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
@Override
public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry)
    throws IOException {
  if (credential.handleResponse(request, response, supportsRetry)) {
    // If credential decides it can handle it, the return code or message indicated something
    // specific to authentication, and no backoff is desired.
    return true;
  }

  if (delegateHandler.handleResponse(request, response, supportsRetry)) {
    // Otherwise, we defer to the judgement of our internal backoff handler.
    return true;
  }

  if (HttpStatusCodes.isRedirect(response.getStatusCode())
      && request.getFollowRedirects()
      && response.getHeaders() != null
      && response.getHeaders().getLocation() != null) {
    // Hack: Reach in and fix any '+' in the URL but still report 'false'. The client library
    // incorrectly tries to decode '+' into ' ', even though the backend servers treat '+'
    // as a legitimate path character, and so do not encode it. This is safe to do whether
    // or not the client library fixes the bug, since %2B will correctly be decoded as '+'
    // even after the fix.
    String redirectLocation = response.getHeaders().getLocation();
    if (redirectLocation.contains("+")) {
      String escapedLocation = redirectLocation.replace("+", "%2B");
      logger.atFine().log(
          "Redirect path '%s' contains unescaped '+', replacing with '%%2B': '%s'",
          redirectLocation, escapedLocation);
      response.getHeaders().setLocation(escapedLocation);
    }
  }

  return false;
}
 
Example 7
Source File: OAuth2Utils.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
static boolean runningOnComputeEngine(HttpTransport transport,
    SystemEnvironmentProvider environment) {
  // If the environment has requested that we do no GCE checks, return immediately.
  if (Boolean.parseBoolean(environment.getEnv("NO_GCE_CHECK"))) {
    return false;
  }

  GenericUrl tokenUrl = new GenericUrl(getMetadataServerUrl(environment));
  for (int i = 1; i <= MAX_COMPUTE_PING_TRIES; ++i) {
    try {
      HttpRequest request = transport.createRequestFactory().buildGetRequest(tokenUrl);
      request.setConnectTimeout(COMPUTE_PING_CONNECTION_TIMEOUT_MS);
      request.getHeaders().set("Metadata-Flavor", "Google");
      HttpResponse response = request.execute();
      try {
        HttpHeaders headers = response.getHeaders();
        return headersContainValue(headers, "Metadata-Flavor", "Google");
      } finally {
        response.disconnect();
      }
    } catch (SocketTimeoutException expected) {
      // Ignore logging timeouts which is the expected failure mode in non GCE environments.
    } catch (IOException e) {
      LOGGER.log(
          Level.WARNING,
          "Failed to detect whether we are running on Google Compute Engine.",
          e);
    }
  }
  return false;
}
 
Example 8
Source File: AbstractGoogleClientRequest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the metadata request using the given request method to the server and returns the raw
 * metadata {@link HttpResponse}.
 */
private HttpResponse executeUnparsed(boolean usingHead) throws IOException {
  HttpResponse response;
  if (uploader == null) {
    // normal request (not upload)
    response = buildHttpRequest(usingHead).execute();
  } else {
    // upload request
    GenericUrl httpRequestUrl = buildHttpRequestUrl();
    HttpRequest httpRequest = getAbstractGoogleClient()
        .getRequestFactory().buildRequest(requestMethod, httpRequestUrl, httpContent);
    boolean throwExceptionOnExecuteError = httpRequest.getThrowExceptionOnExecuteError();

    response = uploader.setInitiationHeaders(requestHeaders)
        .setDisableGZipContent(disableGZipContent).upload(httpRequestUrl);
    response.getRequest().setParser(getAbstractGoogleClient().getObjectParser());
    // process any error
    if (throwExceptionOnExecuteError && !response.isSuccessStatusCode()) {
      throw newExceptionOnError(response);
    }
  }
  // process response
  lastResponseHeaders = response.getHeaders();
  lastStatusCode = response.getStatusCode();
  lastStatusMessage = response.getStatusMessage();
  return response;
}
 
Example 9
Source File: TokenResponseException.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new instance of {@link TokenResponseException}.
 *
 * <p>
 * If there is a JSON error response, it is parsed using {@link TokenErrorResponse}, which can be
 * inspected using {@link #getDetails()}. Otherwise, the full response content is read and
 * included in the exception message.
 * </p>
 *
 * @param jsonFactory JSON factory
 * @param response HTTP response
 * @return new instance of {@link TokenErrorResponse}
 */
public static TokenResponseException from(JsonFactory jsonFactory, HttpResponse response) {
  HttpResponseException.Builder builder = new HttpResponseException.Builder(
      response.getStatusCode(), response.getStatusMessage(), response.getHeaders());
  // details
  Preconditions.checkNotNull(jsonFactory);
  TokenErrorResponse details = null;
  String detailString = null;
  String contentType = response.getContentType();
  try {
    if (!response.isSuccessStatusCode() && contentType != null && response.getContent() != null
        && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, contentType)) {
      details = new JsonObjectParser(jsonFactory).parseAndClose(
          response.getContent(), response.getContentCharset(), TokenErrorResponse.class);
      detailString = details.toPrettyString();
    } else {
      detailString = response.parseAsString();
    }
  } catch (IOException exception) {
    // it would be bad to throw an exception while throwing an exception
    exception.printStackTrace();
  }
  // message
  StringBuilder message = HttpResponseException.computeMessageBuffer(response);
  if (!com.google.api.client.util.Strings.isNullOrEmpty(detailString)) {
    message.append(StringUtils.LINE_SEPARATOR).append(detailString);
    builder.setContent(detailString);
  }
  builder.setMessage(message.toString());
  return new TokenResponseException(builder, details);
}
 
Example 10
Source File: BatchJobUploader.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Initiates the resumable upload by sending a request to Google Cloud Storage.
 *
 * @param batchJobUploadUrl the {@code uploadUrl} of a {@code BatchJob}
 * @return the URI for the initiated resumable upload
 */
private URI initiateResumableUpload(URI batchJobUploadUrl) throws BatchJobException {
  // This follows the Google Cloud Storage guidelines for initiating resumable uploads:
  // https://cloud.google.com/storage/docs/resumable-uploads-xml
  HttpRequestFactory requestFactory =
      httpTransport.createRequestFactory(
          req -> {
            HttpHeaders headers = createHttpHeaders();
            headers.setContentLength(0L);
            headers.set("x-goog-resumable", "start");
            req.setHeaders(headers);
            req.setLoggingEnabled(true);
          });

  try {
    HttpRequest httpRequest =
        requestFactory.buildPostRequest(new GenericUrl(batchJobUploadUrl), new EmptyContent());
    HttpResponse response = httpRequest.execute();
    if (response.getHeaders() == null || response.getHeaders().getLocation() == null) {
      throw new BatchJobException(
          "Initiate upload failed. Resumable upload URI was not in the response.");
    }
    return URI.create(response.getHeaders().getLocation());
  } catch (IOException e) {
    throw new BatchJobException("Failed to initiate upload", e);
  }
}
 
Example 11
Source File: LenientTokenResponseException.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new instance of {@link LenientTokenResponseException}.
 * <p>
 * If there is a JSON error response, it is parsed using
 * {@link TokenErrorResponse}, which can be inspected using
 * {@link #getDetails()}. Otherwise, the full response content is read and
 * included in the exception message.
 * </p>
 * 
 * @param jsonFactory JSON factory
 * @param readResponse an HTTP response that has already been read
 * @param responseContent the content String of the HTTP response
 * @return new instance of {@link TokenErrorResponse}
 */
public static LenientTokenResponseException from(JsonFactory jsonFactory,
        HttpResponse readResponse, String responseContent) {
    HttpResponseException.Builder builder = new HttpResponseException.Builder(
            readResponse.getStatusCode(), readResponse.getStatusMessage(),
            readResponse.getHeaders());
    // details
    Preconditions.checkNotNull(jsonFactory);
    TokenErrorResponse details = null;
    String detailString = null;
    String contentType = readResponse.getContentType();
    try {
        if (/* !response.isSuccessStatusCode() && */true
                && contentType != null
                && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, contentType)) {
            details = readResponse
                    .getRequest()
                    .getParser()
                    .parseAndClose(new StringReader(responseContent), TokenErrorResponse.class);
            detailString = details.toPrettyString();
        } else {
            detailString = responseContent;
        }
    } catch (IOException exception) {
        // it would be bad to throw an exception while throwing an exception
        exception.printStackTrace();
    }
    // message
    StringBuilder message = HttpResponseException.computeMessageBuffer(readResponse);
    if (!com.google.api.client.util.Strings.isNullOrEmpty(detailString)) {
        message.append(StringUtils.LINE_SEPARATOR).append(detailString);
        builder.setContent(detailString);
    }
    builder.setMessage(message.toString());
    return new LenientTokenResponseException(builder, details);
}
 
Example 12
Source File: PrintUtil.java    From apigee-deploy-maven-plugin with Apache License 2.0 3 votes vote down vote up
public static String formatResponse(HttpResponse response, String body) {

        String prettyString = "Response returned by the server \n **************************\n";

        // Print all headers except auth

        prettyString = prettyString + response.getStatusCode() + "  " + response.getStatusMessage();

        HttpHeaders headers = response.getHeaders();

        Set<String> tempheadersmap = headers.keySet();

        for (Iterator<String> iter = tempheadersmap.iterator(); iter.hasNext(); ) {

            try {
                String headerkey = iter.next();
                if (!headerkey.trim().equalsIgnoreCase("Authorization")) {
                    String headervalue = ""+headers.get(headerkey);
                    prettyString = prettyString + "\n" + headerkey + ": " + headervalue;
                }

            } catch (Exception e) {
				log.error(e.getMessage(), e);
            }

        }

        // print response body
        prettyString = prettyString + "\n" + body;

        return  prettyString;
    }