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

The following examples show how to use com.google.api.client.http.HttpResponse#getContent() . 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: AtomFeedParser.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the given HTTP response using the given feed class and entry class.
 *
 * @param <T> feed type
 * @param <E> entry type
 * @param response HTTP response
 * @param namespaceDictionary XML namespace dictionary
 * @param feedClass feed class
 * @param entryClass entry class
 * @return Atom feed parser
 * @throws IOException I/O exception
 * @throws XmlPullParserException XML pull parser exception
 */
public static <T, E> AtomFeedParser<T, E> create(
    HttpResponse response,
    XmlNamespaceDictionary namespaceDictionary,
    Class<T> feedClass,
    Class<E> entryClass)
    throws IOException, XmlPullParserException {
  InputStream content = response.getContent();
  try {
    Atom.checkContentType(response.getContentType());
    XmlPullParser parser = Xml.createParser();
    parser.setInput(content, null);
    AtomFeedParser<T, E> result =
        new AtomFeedParser<T, E>(namespaceDictionary, parser, content, feedClass, entryClass);
    content = null;
    return result;
  } finally {
    if (content != null) {
      content.close();
    }
  }
}
 
Example 2
Source File: RemoteGoogleDriveConnector.java    From cloudsync with GNU General Public License v2.0 6 votes vote down vote up
@Override
public InputStream get(final Handler handler, final Item item) throws CloudsyncException
{
	initService(handler);

	int retryCount = 0;
	do
	{
		try
		{
			refreshCredential();

			final File driveItem = _getDriveItem(item);
			final String downloadUrl = driveItem.getDownloadUrl();
			final HttpResponse resp = service.getRequestFactory().buildGetRequest(new GenericUrl(downloadUrl)).execute();
			return resp.getContent();
		}
		catch (final IOException e)
		{
			retryCount = validateException("remote get", item, e, retryCount);
			if(retryCount < 0) // TODO workaround - fix this later
				retryCount = 0;
		}
	}
	while (true);
}
 
Example 3
Source File: MultiKindFeedParser.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the given HTTP response using the given feed class and entry classes.
 *
 * @param <T> feed type
 * @param <E> entry type
 * @param response HTTP response
 * @param namespaceDictionary XML namespace dictionary
 * @param feedClass feed class
 * @param entryClasses entry class
 * @return Atom multi-kind feed pull parser
 * @throws IOException I/O exception
 * @throws XmlPullParserException XML pull parser exception
 */
public static <T, E> MultiKindFeedParser<T> create(HttpResponse response,
    XmlNamespaceDictionary namespaceDictionary, Class<T> feedClass, Class<E>... entryClasses)
    throws IOException, XmlPullParserException {
  InputStream content = response.getContent();
  try {
    Atom.checkContentType(response.getContentType());
    XmlPullParser parser = Xml.createParser();
    parser.setInput(content, null);
    MultiKindFeedParser<T> result =
        new MultiKindFeedParser<T>(namespaceDictionary, parser, content, feedClass);
    result.setEntryClasses(entryClasses);
    return result;
  } finally {
    content.close();
  }
}
 
Example 4
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 5
Source File: TestUtils.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Override
public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry)
    throws IOException {
  System.out.println(response.getStatusCode());
  BufferedReader in = new BufferedReader(new InputStreamReader(response.getContent()));
  String line;
  while ((line = in.readLine()) != null) {
    System.out.println(line);
  }
  return false;
}
 
Example 6
Source File: SyncTestUtils.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the content of a file on Google Drive.
 * 
 * @param file file to read
 * @param drive a Google Drive object
 * @return the string content of the file
 * @throws IOException
 */
public static String getContentOfFile(File file, Drive drive) throws IOException {
  HttpResponse resp = drive.getRequestFactory()
      .buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();
  BufferedReader br = new BufferedReader(new InputStreamReader(resp.getContent()));
  StringBuilder sb = new StringBuilder();
  String line;
  while ((line = br.readLine()) != null) {
    sb.append(line);
  }
  String fileContent = sb.toString();
  br.close();
  return fileContent;
}
 
Example 7
Source File: UpdateRegistrarRdapBaseUrlsAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private ImmutableSetMultimap<String, String> getRdapBaseUrlsPerIanaIdWithTld(
    String tld, String id, HttpRequestFactory requestFactory) {
  String content;
  try {
    HttpRequest request =
        requestFactory.buildGetRequest(new GenericUrl(String.format(LIST_URL, tld)));
    request.getHeaders().setAcceptEncoding("identity");
    request.getHeaders().setCookie(String.format("%s=%s", COOKIE_ID, id));
    HttpResponse response = request.execute();

    try (InputStream input = response.getContent()) {
      content = new String(ByteStreams.toByteArray(input), UTF_8);
    }
  } catch (IOException e) {
    throw new UncheckedIOException(
        "Error reading RDAP list from MoSAPI server: " + e.getMessage(), e);
  } finally {
    logout(requestFactory, id, tld);
  }

  logger.atInfo().log("list reply: '%s'", content);
  JsonObject listReply = new Gson().fromJson(content, JsonObject.class);
  JsonArray services = listReply.getAsJsonArray("services");
  // The format of the response "services" is an array of "ianaIDs to baseUrls", where "ianaIDs
  // to baseUrls" is an array of size 2 where the first item is all the "iana IDs" and the
  // second item all the "baseUrls".
  ImmutableSetMultimap.Builder<String, String> builder = new ImmutableSetMultimap.Builder<>();
  for (JsonElement service : services) {
    for (JsonElement ianaId : service.getAsJsonArray().get(0).getAsJsonArray()) {
      for (JsonElement baseUrl : service.getAsJsonArray().get(1).getAsJsonArray()) {
        builder.put(ianaId.getAsString(), baseUrl.getAsString());
      }
    }
  }

  return builder.build();
}
 
Example 8
Source File: BuyerServiceHelper.java    From googleads-adxbuyer-examples with Apache License 2.0 5 votes vote down vote up
/**
 * reads results from the response object and converts them to a String
 * @param response you want to read content from
 * @return the response content as a String
 * @throws IOException
 */
protected static String getResultAsString(HttpResponse response) throws IOException {
  InputStream content = response.getContent();
  if (content == null) {
    return "";
  }
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  IOUtils.copy(content, out);
  String json = out.toString(response.getContentCharset().name());
  return json;
}
 
Example 9
Source File: GoogleCloudStorageReadChannel.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
private void cacheFooter(HttpResponse response) throws IOException {
  checkState(size > 0, "size should be greater than 0 for '%s'", resourceId);
  int footerSize = Math.toIntExact(response.getHeaders().getContentLength());
  footerContent = new byte[footerSize];
  try (InputStream footerStream = response.getContent()) {
    int totalBytesRead = 0;
    int bytesRead = 0;
    do {
      totalBytesRead += bytesRead;
      bytesRead = footerStream.read(footerContent, totalBytesRead, footerSize - totalBytesRead);
    } while (bytesRead >= 0 && totalBytesRead <= footerSize);
    checkState(
        footerStream.read() < 0,
        "footerStream should be empty after reading %s bytes from %s bytes for '%s'",
        totalBytesRead,
        footerSize,
        resourceId);
    checkState(
        totalBytesRead == footerSize,
        "totalBytesRead (%s) should equal footerSize (%s) for '%s'",
        totalBytesRead,
        footerSize,
        resourceId);
  } catch (IOException e) {
    footerContent = null;
    throw e;
  }
  logger.atFine().log("Prefetched %s bytes footer for '%s'", footerContent.length, resourceId);
}
 
Example 10
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 11
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 12
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 13
Source File: HttpResponseUtils.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
static String parseAsStringWithoutClosing(HttpResponse response) throws IOException {
    InputStream content = response.getContent();
    if (content == null) {
        return "";
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copy(content, out, false);
    return out.toString(response.getContentCharset().name());
}
 
Example 14
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 15
Source File: BatchRequest.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
/**
 * Executes all queued HTTP requests in a single call, parses the responses and invokes callbacks.
 *
 * <p>
 * Calling {@link #execute()} executes and clears the queued requests. This means that the
 * {@link BatchRequest} object can be reused to {@link #queue} and {@link #execute()} requests
 * again.
 * </p>
 */
public void execute() throws IOException {
  boolean retryAllowed;
  Preconditions.checkState(!requestInfos.isEmpty());

  // Log a warning if the user is using the global batch endpoint. In the future, we can turn this
  // into a preconditions check.
  if (GLOBAL_BATCH_ENDPOINT.equals(this.batchUrl.toString())) {
    LOGGER.log(Level.WARNING, GLOBAL_BATCH_ENDPOINT_WARNING);
  }

  HttpRequest batchRequest = requestFactory.buildPostRequest(this.batchUrl, null);
  // NOTE: batch does not support gzip encoding
  HttpExecuteInterceptor originalInterceptor = batchRequest.getInterceptor();
  batchRequest.setInterceptor(new BatchInterceptor(originalInterceptor));
  int retriesRemaining = batchRequest.getNumberOfRetries();

  do {
    retryAllowed = retriesRemaining > 0;
    MultipartContent batchContent = new MultipartContent();
    batchContent.getMediaType().setSubType("mixed");
    int contentId = 1;
    for (RequestInfo<?, ?> requestInfo : requestInfos) {
      batchContent.addPart(new MultipartContent.Part(
          new HttpHeaders().setAcceptEncoding(null).set("Content-ID", contentId++),
          new HttpRequestContent(requestInfo.request)));
    }
    batchRequest.setContent(batchContent);
    HttpResponse response = batchRequest.execute();
    BatchUnparsedResponse batchResponse;
    try {
      // Find the boundary from the Content-Type header.
      String boundary = "--" + response.getMediaType().getParameter("boundary");

      // Parse the content stream.
      InputStream contentStream = response.getContent();
      batchResponse =
          new BatchUnparsedResponse(contentStream, boundary, requestInfos, retryAllowed);

      while (batchResponse.hasNext) {
        batchResponse.parseNextResponse();
      }
    } finally {
      response.disconnect();
    }

    List<RequestInfo<?, ?>> unsuccessfulRequestInfos = batchResponse.unsuccessfulRequestInfos;
    if (!unsuccessfulRequestInfos.isEmpty()) {
      requestInfos = unsuccessfulRequestInfos;
    } else {
      break;
    }
    retriesRemaining--;
  } while (retryAllowed);
  requestInfos.clear();
}
 
Example 16
Source File: OAuth2WebViewActivity.java    From apigee-android-sdk with Apache License 2.0 4 votes vote down vote up
@Override
protected Void doInBackground(String...params) {
    if (this.url.startsWith(this.redirectURL))
    {
        OAuth2WebViewActivity.this.handledRedirect = true;
        this.resultIntent = new Intent();
        try {
            Map<String,String> urlQueryParams = this.extractQueryParams(url);
            if( urlQueryParams.get(OAuth2AccessTokenExtraKey) != null ) {
                this.resultIntent.putExtra(OAuth2AccessTokenExtraKey,urlQueryParams.get(OAuth2AccessTokenExtraKey));
                if( urlQueryParams.get(OAuth2ExpiresInExtraKey) != null ) {
                    this.resultIntent.putExtra(OAuth2ExpiresInExtraKey,urlQueryParams.get(OAuth2ExpiresInExtraKey));
                }
                if( urlQueryParams.get(OAuth2RefreshTokenExtraKey) != null ) {
                    this.resultIntent.putExtra(OAuth2RefreshTokenExtraKey, urlQueryParams.get(OAuth2RefreshTokenExtraKey));
                }
            } else if ( urlQueryParams.get(OAuth2AccessCodeExtraKey) != null ) {
                String authorizationCode = urlQueryParams.get(OAuth2AccessCodeExtraKey);
                resultIntent.putExtra(OAuth2AccessCodeExtraKey, authorizationCode);

                OAuth2WebViewActivity.this.setResult(RESULT_OK,resultIntent);

                AuthorizationCodeTokenRequest codeTokenRequest = new AuthorizationCodeTokenRequest(new NetHttpTransport(),new JacksonFactory(),new GenericUrl(this.accessTokenURL),authorizationCode);
                codeTokenRequest.setRedirectUri(this.redirectURL);
                if( clientId != null ) {
                    codeTokenRequest.set("client_id", clientId);
                }
                if( clientSecret != null ) {
                    codeTokenRequest.set("client_secret", clientSecret);
                }
                HttpResponse response  = codeTokenRequest.executeUnparsed();

                InputStream in = response.getContent();
                InputStreamReader is = new InputStreamReader(in);
                StringBuilder sb=new StringBuilder();
                BufferedReader br = new BufferedReader(is);
                String read = br.readLine();

                while(read != null) {
                    sb.append(read);
                    read =br.readLine();
                }

                String accessTokenStringData = sb.toString();
                Map<String,String> queryParams = this.extractQueryParams(accessTokenStringData);
                if( queryParams.get(OAuth2AccessTokenExtraKey) != null ) {
                    this.resultIntent.putExtra(OAuth2AccessTokenExtraKey,queryParams.get(OAuth2AccessTokenExtraKey));
                }
                if( queryParams.get(OAuth2ExpiresInExtraKey) != null ) {
                    this.resultIntent.putExtra(OAuth2ExpiresInExtraKey, queryParams.get(OAuth2ExpiresInExtraKey));
                }
                if( queryParams.get(OAuth2RefreshTokenExtraKey) != null ) {
                    this.resultIntent.putExtra(OAuth2RefreshTokenExtraKey, queryParams.get(OAuth2RefreshTokenExtraKey));
                }
            } else if (urlQueryParams.get(OAuth2ErrorExtraKey) != null) {
                this.resultIntent.putExtra(OAuth2ErrorExtraKey,urlQueryParams.get(OAuth2ErrorExtraKey));
                OAuth2WebViewActivity.this.setResult(RESULT_OK, resultIntent);
            }
        } catch (Exception e) {
            this.resultIntent.putExtra("error",e.getLocalizedMessage());
            e.printStackTrace();
        }
    }
    return null;
}