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

The following examples show how to use com.google.api.client.http.HttpResponse#getStatusMessage() . 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: RememberTheMilkService.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private <T extends RememberTheMilkResponse> T makeRequest(
    Map<String, String> parameters, Class<T> dataClass) throws IOException {

  URL signedUrl = signatureGenerator.getSignature(BASE_URL, parameters);

  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest getRequest = requestFactory.buildGetRequest(new GenericUrl(signedUrl));
  HttpResponse response = getRequest.execute();
  int statusCode = response.getStatusCode();
  if (statusCode != 200) {
    throw new IOException(
        "Bad status code: " + statusCode + " error: " + response.getStatusMessage());
  }

  T parsedResponse = xmlMapper.readValue(response.getContent(), dataClass);

  if (parsedResponse.error != null) {
    throw new IOException(
        "Error making call to " + signedUrl + " error: " + parsedResponse.error);
  }

  return parsedResponse;
}
 
Example 2
Source File: RememberTheMilkAuthDataGenerator.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private String getToken(String frob) throws IOException {
  URL signedUrl =
      signatureGenerator.getSignature(
          GET_TOKEN_URL, ImmutableMap.of("frob", frob, "method", GET_TOKEN_METHOD));

  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest getRequest = requestFactory.buildGetRequest(new GenericUrl(signedUrl));
  HttpResponse response = getRequest.execute();
  int statusCode = response.getStatusCode();
  if (statusCode != 200) {
    throw new IOException(
        "Bad status code: " + statusCode + " error: " + response.getStatusMessage());
  }

  AuthElement authElement = xmlMapper.readValue(response.getContent(), AuthElement.class);

  Preconditions.checkState(authElement.stat.equals("ok"), "state must be ok: %s", authElement);
  Preconditions.checkState(
      !Strings.isNullOrEmpty(authElement.auth.token), "token must not be empty", authElement);
  return authElement.auth.token;
}
 
Example 3
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 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: 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 6
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 7
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 8
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 9
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 10
Source File: SolidUtilities.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the contents of a URL to produce an RDF model.
 */
public Model getModel(String url) throws IOException {
  HttpRequestFactory factory = TRANSPORT.createRequestFactory();

  HttpRequest rootGetRequest = factory.buildGetRequest(
      new GenericUrl(url));
  HttpHeaders headers = new HttpHeaders();
  headers.setCookie(authCookie);
  headers.setAccept("text/turtle");
  rootGetRequest.setHeaders(headers);

  HttpResponse response = rootGetRequest.execute();
  if (response.getStatusCode() != 200) {
    throw new IOException("Unexpected return code: "
        + response.getStatusCode()
        + "\nMessage:\n"
        + response.getStatusMessage());

  }
  StringWriter writer = new StringWriter();
  IOUtils.copy(response.getContent(), writer, "UTF-8");
  String fixedString = fixProblematicPeriods(writer.toString());
  Model defaultModel = ModelFactory.createDefaultModel();
  return defaultModel.read(
      new StringReader(fixedString),
      url,
      "TURTLE");
}
 
Example 11
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 12
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 13
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 14
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 15
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 16
Source File: LabelsSample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Add or modify a label on a dataset.
 *
 * See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
 * documentation</a>.
 */
public static void labelDataset(
    String projectId, String datasetId, String labelKey, String labelValue) throws IOException {

  // Authenticate requests using Google Application Default credentials.
  GoogleCredentials credential = GoogleCredentials.getApplicationDefault();
  credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));

  // Get a new access token.
  // Note that access tokens have an expiration. You can reuse a token rather than requesting a
  // new one if it is not yet expired.
  AccessToken accessToken = credential.refreshAccessToken();

  // Set the content of the request.
  Dataset dataset = new Dataset();
  dataset.addLabel(labelKey, labelValue);
  HttpContent content = new JsonHttpContent(JSON_FACTORY, dataset);

  // Send the request to the BigQuery API.
  String urlFormat =
      "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s"
          + "?fields=labels&access_token=%s";
  GenericUrl url =
      new GenericUrl(String.format(urlFormat, projectId, datasetId, accessToken.getTokenValue()));
  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(url, content);
  request.setParser(JSON_FACTORY.createJsonObjectParser());

  // Workaround for transports which do not support PATCH requests.
  // See: http://stackoverflow.com/a/32503192/101923
  request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
  HttpResponse response = request.execute();

  // Check for errors.
  if (response.getStatusCode() != 200) {
    throw new RuntimeException(response.getStatusMessage());
  }

  Dataset responseDataset = response.parseAs(Dataset.class);
  System.out.printf(
      "Updated label \"%s\" with value \"%s\"\n",
      labelKey, responseDataset.getLabels().get(labelKey));
}
 
Example 17
Source File: LabelsSample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Add or modify a label on a table.
 *
 * See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
 * documentation</a>.
 */
public static void labelTable(
    String projectId, String datasetId, String tableId, String labelKey, String labelValue)
    throws IOException {

  // Authenticate requests using Google Application Default credentials.
  GoogleCredentials credential = GoogleCredentials.getApplicationDefault();
  credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));

  // Get a new access token.
  // Note that access tokens have an expiration. You can reuse a token rather than requesting a
  // new one if it is not yet expired.
  AccessToken accessToken = credential.refreshAccessToken();

  // Set the content of the request.
  Table table = new Table();
  table.addLabel(labelKey, labelValue);
  HttpContent content = new JsonHttpContent(JSON_FACTORY, table);

  // Send the request to the BigQuery API.
  String urlFormat =
      "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s/tables/%s"
          + "?fields=labels&access_token=%s";
  GenericUrl url =
      new GenericUrl(
          String.format(urlFormat, projectId, datasetId, tableId, accessToken.getTokenValue()));
  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(url, content);
  request.setParser(JSON_FACTORY.createJsonObjectParser());

  // Workaround for transports which do not support PATCH requests.
  // See: http://stackoverflow.com/a/32503192/101923
  request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
  HttpResponse response = request.execute();

  // Check for errors.
  if (response.getStatusCode() != 200) {
    throw new RuntimeException(response.getStatusMessage());
  }

  Table responseTable = response.parseAs(Table.class);
  System.out.printf(
      "Updated label \"%s\" with value \"%s\"\n",
      labelKey, responseTable.getLabels().get(labelKey));
}
 
Example 18
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;
    }
 
Example 19
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);
}