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

The following examples show how to use com.google.api.client.http.HttpResponse#getStatusCode() . 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: MediaUploadErrorHandler.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry)
    throws IOException {
  boolean handled = originalUnsuccessfulHandler != null
      && originalUnsuccessfulHandler.handleResponse(request, response, supportsRetry);

  // TODO(peleyal): figure out what is best practice - call serverErrorCallback only if the
  // abnormal response was handled, or call it regardless
  if (handled && supportsRetry && response.getStatusCode() / 100 == 5) {
    try {
      uploader.serverErrorCallback();
    } catch (IOException e) {
      LOGGER.log(Level.WARNING, "exception thrown while calling server callback", e);
    }
  }
  return handled;
}
 
Example 3
Source File: RetryUnsuccessfulResponseHandler.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleResponse(
    HttpRequest request, HttpResponse response, boolean supportsRetry) throws IOException {

  if (!supportsRetry) {
    return false;
  }

  int statusCode = response.getStatusCode();
  if (!retryConfig.getRetryStatusCodes().contains(statusCode)) {
    return false;
  }

  try {
    return waitAndRetry(response);
  } catch (InterruptedException e) {
    // ignore
  }
  return false;
}
 
Example 4
Source File: DeezerApi.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private <T> T makeRequest(String url, Class<T> clazz)
    throws IOException {
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
  HttpRequest getRequest =
      requestFactory.buildGetRequest(
          new GenericUrl(url + "?output=json&access_token=" + accessToken));
  perUserRateLimiter.acquire();
  HttpResponse response = getRequest.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));
  return MAPPER.readValue(result, clazz);
}
 
Example 5
Source File: InstagramPhotoExporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private <T> T makeRequest(String url, Class<T> clazz, TokensAndUrlAuthData authData)
    throws IOException {
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
  HttpRequest getRequest =
      requestFactory.buildGetRequest(
          new GenericUrl(url + "?access_token=" + authData.getAccessToken()));
  HttpResponse response = getRequest.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));
  return objectMapper.readValue(result, clazz);
}
 
Example 6
Source File: OAuthUtils.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
static String makeRawPostRequest(HttpTransport httpTransport, String url, HttpContent httpContent)
    throws IOException {
  HttpRequestFactory factory = httpTransport.createRequestFactory();
  HttpRequest postRequest = factory.buildPostRequest(new GenericUrl(url), httpContent);
  HttpResponse response = postRequest.execute();
  int statusCode = response.getStatusCode();
  if (statusCode != 200) {
    throw new IOException(
        "Bad status code: " + statusCode + " error: " + response.getStatusMessage());
  }
  return CharStreams
      .toString(new InputStreamReader(response.getContent(), Charsets.UTF_8));
}
 
Example 7
Source File: HttpHandler.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new Axis Message based on the contents of the HTTP response.
 *
 * @param httpResponse the HTTP response
 * @return an Axis Message for the HTTP response
 * @throws IOException if unable to retrieve the HTTP response's contents
 * @throws AxisFault if the HTTP response's status or contents indicate an unexpected error, such
 *     as a 405.
 */
private Message createResponseMessage(HttpResponse httpResponse) throws IOException, AxisFault {
  int statusCode = httpResponse.getStatusCode();
  String contentType = httpResponse.getContentType();
  // The conditions below duplicate the logic in CommonsHTTPSender and HTTPSender.
  boolean shouldParseResponse =
      (statusCode > 199 && statusCode < 300)
          || (contentType != null
              && !contentType.equals("text/html")
              && statusCode > 499
              && statusCode < 600);
  // Wrap the content input stream in a notifying stream so the stream event listener will be
  // notified when it is closed.
  InputStream responseInputStream =
      new NotifyingInputStream(httpResponse.getContent(), inputStreamEventListener);
  if (!shouldParseResponse) {
    // The contents are not an XML response, so throw an AxisFault with
    // the HTTP status code and message details.
    String statusMessage = httpResponse.getStatusMessage();
    AxisFault axisFault =
        new AxisFault("HTTP", "(" + statusCode + ")" + statusMessage, null, null);
    axisFault.addFaultDetail(
        Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, String.valueOf(statusCode));
    try (InputStream stream = responseInputStream) {
      byte[] contentBytes = ByteStreams.toByteArray(stream);
      axisFault.setFaultDetailString(
          Messages.getMessage(
              "return01", String.valueOf(statusCode), new String(contentBytes, UTF_8)));
    }
    throw axisFault;
  }
  // Response is an XML response. Do not consume and close the stream in this case, since that
  // will happen later when the response is deserialized by Axis (as confirmed by unit tests for
  // this class).
  Message responseMessage =
      new Message(
          responseInputStream, false, contentType, httpResponse.getHeaders().getLocation());
  responseMessage.setMessageType(Message.RESPONSE);
  return responseMessage;
}
 
Example 8
Source File: CloudClientLibGenerator.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
InputStream postRequest(String url, String boundary, String content) throws IOException {
  HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(url),
      ByteArrayContent.fromString("multipart/form-data; boundary=" + boundary, content));
  request.setReadTimeout(60000);  // 60 seconds is the max App Engine request time
  HttpResponse response = request.execute();
  if (response.getStatusCode() >= 300) {
    throw new IOException("Client Generation failed at server side: " + response.getContent());
  } else {
    return response.getContent();
  }
}
 
Example 9
Source File: GoogleAccountCredential.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry)
    throws IOException {
  try {
    if (response.getStatusCode() == 401 && !received401) {
      received401 = true;
      GoogleAuthUtil.clearToken(context, token);
      return true;
    }
  } catch (GoogleAuthException e) {
    throw new GoogleAuthIOException(e);
  }
  return false;
}
 
Example 10
Source File: HttpResponseUtils.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
static boolean hasMessageBody(HttpResponse response) throws IOException {
    int statusCode = response.getStatusCode();
    if (response.getRequest().getRequestMethod().equals(HttpMethods.HEAD)
            || statusCode / 100 == 1
            || statusCode == HttpStatusCodes.STATUS_CODE_NO_CONTENT
            || statusCode == HttpStatusCodes.STATUS_CODE_NOT_MODIFIED) {
        response.ignore();
        return false;
    }
    return true;
}
 
Example 11
Source File: DefaultCredentialProvider.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@Override
protected TokenResponse executeRefreshToken() throws IOException {
  GenericUrl tokenUrl = new GenericUrl(getTokenServerEncodedUrl());
  HttpRequest request = getTransport().createRequestFactory().buildGetRequest(tokenUrl);
  JsonObjectParser parser = new JsonObjectParser(getJsonFactory());
  request.setParser(parser);
  request.getHeaders().set("Metadata-Flavor", "Google");
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  int statusCode = response.getStatusCode();
  if (statusCode == HttpStatusCodes.STATUS_CODE_OK) {
    InputStream content = response.getContent();
    if (content == null) {
      // Throw explicitly rather than allow a later null reference as default mock
      // transports return success codes with empty contents.
      throw new IOException("Empty content from metadata token server request.");
    }
    return parser.parseAndClose(content, response.getContentCharset(), TokenResponse.class);
  }
  if (statusCode == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
    throw new IOException(String.format("Error code %s trying to get security access token from"
        + " Compute Engine metadata for the default service account. This may be because"
        + " the virtual machine instance does not have permission scopes specified.",
        statusCode));
  }
  throw new IOException(String.format("Unexpected Error code %s trying to get security access"
      + " token from Compute Engine metadata for the default service account: %s", statusCode,
      response.parseAsString()));
}
 
Example 12
Source File: DeezerApi.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
private String makePostRequest(String url, Map<String, String> params) throws IOException {
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
  StringBuilder extraArgs = new StringBuilder();
  params.entrySet().forEach(entry -> {
    try {
      extraArgs
          .append("&")
          .append(entry.getKey())
          .append("=")
          .append(URLEncoder.encode(entry.getValue(), "UTF8"));
    } catch (UnsupportedEncodingException e) {
      throw new IllegalArgumentException(e);
    }
  });
  HttpRequest getRequest =
      requestFactory.buildGetRequest(
          new GenericUrl(url
              + "?output=json&request_method=post&access_token=" + accessToken
              + extraArgs));
  perUserRateLimiter.acquire();
  HttpResponse response = getRequest.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));
  return result;
}
 
Example 13
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 14
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 15
Source File: OAuthHmacCredential.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
@Override
public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) {
    if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) {
        // If the token was revoked, we must mark our credential as invalid
        setAccessToken(null);
    }

    // We didn't do anything to fix the problem
    return false;
}
 
Example 16
Source File: RetryHttpInitializer.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
@Override
public boolean handleResponse(
    HttpRequest httpRequest, HttpResponse httpResponse, boolean supportsRetry)
    throws IOException {
  if (responseCodesToLogWithRateLimit.contains(httpResponse.getStatusCode())) {
    switch (httpResponse.getStatusCode()) {
      case HTTP_SC_TOO_MANY_REQUESTS:
        logger.atInfo().atMostEvery(10, SECONDS).log(
            LOG_MESSAGE_FORMAT,
            httpResponse.getStatusCode(),
            httpRequest.getRequestMethod(),
            httpRequest.getUrl());
        break;
      default:
        logger.atInfo().atMostEvery(10, SECONDS).log(
            "Encountered status code %d (and maybe others) when sending %s request to URL '%s'."
                + " Delegating to response handler for possible retry.",
            httpResponse.getStatusCode(), httpRequest.getRequestMethod(), httpRequest.getUrl());
    }
  } else if (responseCodesToLog.contains(httpResponse.getStatusCode())) {
    logger.atInfo().log(
        LOG_MESSAGE_FORMAT,
        httpResponse.getStatusCode(),
        httpRequest.getRequestMethod(),
        httpRequest.getUrl());
  }

  return delegateResponseHandler.handleResponse(httpRequest, httpResponse, supportsRetry);
}
 
Example 17
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 18
Source File: Credential.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * Default implementation checks if {@code WWW-Authenticate} exists and contains a "Bearer" value
 * (see <a href="http://tools.ietf.org/html/rfc6750#section-3.1">rfc6750 section 3.1</a> for more
 * details). If so, it calls {@link #refreshToken} in case the error code contains
 * {@code invalid_token}. If there is no "Bearer" in {@code WWW-Authenticate} and the status code
 * is {@link HttpStatusCodes#STATUS_CODE_UNAUTHORIZED} it calls {@link #refreshToken}. If
 * {@link #executeRefreshToken()} throws an I/O exception, this implementation will log the
 * exception and return {@code false}. Subclasses may override.
 * </p>
 */
public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) {
  boolean refreshToken = false;
  boolean bearer = false;

  List<String> authenticateList = response.getHeaders().getAuthenticateAsList();

  // TODO(peleyal): this logic should be implemented as a pluggable interface, in the same way we
  // implement different AccessMethods

  // if authenticate list is not null we will check if one of the entries contains "Bearer"
  if (authenticateList != null) {
    for (String authenticate : authenticateList) {
      if (authenticate.startsWith(BearerToken.AuthorizationHeaderAccessMethod.HEADER_PREFIX)) {
        // mark that we found a "Bearer" value, and check if there is a invalid_token error
        bearer = true;
        refreshToken = BearerToken.INVALID_TOKEN_ERROR.matcher(authenticate).find();
        break;
      }
    }
  }

  // if "Bearer" wasn't found, we will refresh the token, if we got 401
  if (!bearer) {
    refreshToken = response.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNAUTHORIZED;
  }

  if (refreshToken) {
    try {
      lock.lock();
      try {
        // need to check if another thread has already refreshed the token
        return !Objects.equal(accessToken, method.getAccessTokenFromRequest(request))
            || refreshToken();
      } finally {
        lock.unlock();
      }
    } catch (IOException exception) {
      LOGGER.log(Level.SEVERE, "unable to refresh token", exception);
    }
  }
  return false;
}
 
Example 19
Source File: OAuthClient.java    From kickflip-android-sdk with Apache License 2.0 4 votes vote down vote up
protected boolean isSuccessResponse(HttpResponse response) {
    if (VERBOSE) Log.i(TAG, "Response status code: " + response.getStatusCode());
    return response.getStatusCode() == 200;
}
 
Example 20
Source File: BatchJobUploadResponse.java    From googleads-java-lib with Apache License 2.0 3 votes vote down vote up
/**
 * Constructs a new instance from a {@link HttpResponse}.
 *
 * @param httpResponse the response
 * @param totalContentLength the total content length for the batch job, including the length
 * from this response's corresponding request
 * @param resumableSessionURI the URI to use for further incremental uploads
 * @throws IOException if unable to get attributes of the response
 * @throws NullPointerException is {@code httpResponse} is null.
 */
public BatchJobUploadResponse(HttpResponse httpResponse, long totalContentLength,
    @Nullable URI resumableSessionURI) throws IOException {
  this(Preconditions.checkNotNull(httpResponse, "Null HTTP response").getContent(),
      httpResponse.getStatusCode(), httpResponse.getStatusMessage(), totalContentLength,
      resumableSessionURI);
}