Java Code Examples for com.google.api.client.http.HttpResponse#parseAsString()
The following examples show how to use
com.google.api.client.http.HttpResponse#parseAsString() .
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: BuildAndVerifyIapRequestIT.java From java-docs-samples with Apache License 2.0 | 6 votes |
@Test public void testGenerateAndVerifyIapRequestIsSuccessful() throws Exception { HttpRequest request = httpTransport.createRequestFactory().buildGetRequest(new GenericUrl(IAP_PROTECTED_URL)); HttpRequest iapRequest = BuildIapRequest.buildIapRequest(request, IAP_CLIENT_ID); HttpResponse response = iapRequest.execute(); assertEquals(response.getStatusCode(), HttpStatus.SC_OK); String headerWithtoken = response.parseAsString(); String[] split = headerWithtoken.split(":"); assertNotNull(split); assertEquals(2, split.length); assertEquals("x-goog-authenticated-user-jwt", split[0].trim()); String jwtToken = split[1].trim(); HttpRequest verifyJwtRequest = httpTransport .createRequestFactory() .buildGetRequest(new GenericUrl(IAP_PROTECTED_URL)) .setHeaders(new HttpHeaders().set("x-goog-iap-jwt-assertion", jwtToken)); boolean verified = verifyIapRequestHeader.verifyJwtForAppEngine( verifyJwtRequest, IAP_PROJECT_NUMBER, IAP_PROJECT_ID); assertTrue(verified); }
Example 2
Source File: StorageSample.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** * Fetches the listing of the given bucket. * * @param bucketName the name of the bucket to list. * @return the raw XML containing the listing of the bucket. * @throws IOException if there's an error communicating with Cloud Storage. * @throws GeneralSecurityException for errors creating https connection. */ public static String listBucket(final String bucketName) throws IOException, GeneralSecurityException { // [START snippet] // Build an account credential. GoogleCredentials credential = GoogleCredentials.getApplicationDefault() .createScoped(Collections.singleton(STORAGE_SCOPE)); // Set up and execute a Google Cloud Storage request. String uri = "https://storage.googleapis.com/" + URLEncoder.encode(bucketName, "UTF-8"); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); HttpRequestFactory requestFactory = httpTransport.createRequestFactory(new HttpCredentialsAdapter(credential)); GenericUrl url = new GenericUrl(uri); HttpRequest request = requestFactory.buildGetRequest(url); HttpResponse response = request.execute(); String content = response.parseAsString(); // [END snippet] return content; }
Example 3
Source File: GitHubRequest.java From android-oauth-client with Apache License 2.0 | 6 votes |
@Override public T execute() throws IOException { HttpResponse response = super.executeUnparsed(); ObjectParser parser = response.getRequest().getParser(); // This will degrade parsing performance but is an inevitable workaround // for the inability to parse JSON arrays. String content = response.parseAsString(); if (response.isSuccessStatusCode() && !TextUtils.isEmpty(content) && content.charAt(0) == '[') { content = TextUtils.concat("{\"", GitHubResponse.KEY_DATA, "\":", content, "}") .toString(); } Reader reader = new StringReader(content); T parsedResponse = parser.parseAndClose(reader, getResponseClass()); // parse pagination from Link header if (parsedResponse instanceof GitHubResponse) { Pagination pagination = new Pagination(response.getHeaders().getFirstHeaderStringValue("Link")); ((GitHubResponse) parsedResponse).setPagination(pagination); } return parsedResponse; }
Example 4
Source File: TwitterRequest.java From android-oauth-client with Apache License 2.0 | 6 votes |
@Override public T execute() throws IOException { HttpResponse response = super.executeUnparsed(); ObjectParser parser = response.getRequest().getParser(); // This will degrade parsing performance but is an inevitable workaround // for the inability to parse JSON arrays. String content = response.parseAsString(); if (response.isSuccessStatusCode() && !TextUtils.isEmpty(content) && content.charAt(0) == '[') { content = TextUtils.concat("{\"", TwitterResponse.KEY_DATA, "\":", content, "}") .toString(); } Reader reader = new StringReader(content); return parser.parseAndClose(reader, getResponseClass()); }
Example 5
Source File: LookupControllerTest.java From reposilite with Apache License 2.0 | 5 votes |
@Test void shouldReturn200AndProxiedFile() throws Exception { super.reposilite.getConfiguration().setProxied(Collections.singletonList("http://localhost:8080")); try { System.setProperty("reposilite.port", "8080"); Reposilite proxiedReposilite = super.reposilite(proxiedWorkingDirectory); proxiedReposilite.launch(); File proxiedFile = new File(proxiedWorkingDirectory, "/repositories/releases/proxiedGroup/proxiedArtifact/proxied.txt"); proxiedFile.getParentFile().mkdirs(); proxiedFile.createNewFile(); FileUtils.overrideFile(proxiedFile, "proxied content"); HttpResponse response = get("/releases/proxiedGroup/proxiedArtifact/proxied.txt"); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); String content = response.parseAsString(); assertEquals("proxied content", content); System.out.println(content); proxiedReposilite.shutdown(); } finally { System.clearProperty("reposilite.port"); } }
Example 6
Source File: HttpClient.java From steem-java-api-wrapper with GNU General Public License v3.0 | 5 votes |
@Override public JsonRPCResponse invokeAndReadResponse(JsonRPCRequest requestObject, URI endpointUri, boolean sslVerificationDisabled) throws SteemCommunicationException { try { NetHttpTransport.Builder builder = new NetHttpTransport.Builder(); // Disable SSL verification if needed if (sslVerificationDisabled && endpointUri.getScheme().equals("https")) { builder.doNotValidateCertificate(); } String requestPayload = requestObject.toJson(); HttpRequest httpRequest = builder.build().createRequestFactory(new HttpClientRequestInitializer()) .buildPostRequest(new GenericUrl(endpointUri), ByteArrayContent.fromString("application/json", requestPayload)); LOGGER.debug("Sending {}.", requestPayload); HttpResponse httpResponse = httpRequest.execute(); int status = httpResponse.getStatusCode(); String responsePayload = httpResponse.parseAsString(); if (status >= 200 && status < 300 && responsePayload != null) { return new JsonRPCResponse(CommunicationHandler.getObjectMapper().readTree(responsePayload)); } else { throw new ClientProtocolException("Unexpected response status: " + status); } } catch (GeneralSecurityException | IOException e) { throw new SteemCommunicationException("A problem occured while processing the request.", e); } }
Example 7
Source File: StorageSample.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { try { AppIdentityCredential credential = new AppIdentityCredential(Arrays.asList(STORAGE_SCOPE)); // Set up and execute Google Cloud Storage request. String bucketName = req.getRequestURI(); if (bucketName.equals("/")) { resp.sendError( HTTP_NOT_FOUND, "No bucket specified - append /bucket-name to the URL and retry."); return; } // Remove any trailing slashes, if found. // [START snippet] String cleanBucketName = bucketName.replaceAll("/$", ""); String uri = GCS_URI + cleanBucketName; HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential); GenericUrl url = new GenericUrl(uri); HttpRequest request = requestFactory.buildGetRequest(url); HttpResponse response = request.execute(); String content = response.parseAsString(); // [END snippet] // Display the output XML. resp.setContentType("text/xml"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(resp.getOutputStream())); String formattedContent = content.replaceAll("(<ListBucketResult)", XSL + "$1"); writer.append(formattedContent); writer.flush(); resp.setStatus(HTTP_OK); } catch (Throwable e) { resp.sendError(HTTP_NOT_FOUND, e.getMessage()); } }
Example 8
Source File: StorageSample.java From cloud-storage-docs-xml-api-examples with Apache License 2.0 | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { AppIdentityCredential credential = new AppIdentityCredential(Arrays.asList(STORAGE_SCOPE)); // Set up and execute Google Cloud Storage request. String bucketName = req.getRequestURI(); if (bucketName.equals("/")) { resp.sendError(404, "No bucket specified - append /bucket-name to the URL and retry."); return; } // Remove any trailing slashes, if found. //[START snippet] String cleanBucketName = bucketName.replaceAll("/$", ""); String URI = GCS_URI + cleanBucketName; HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential); GenericUrl url = new GenericUrl(URI); HttpRequest request = requestFactory.buildGetRequest(url); HttpResponse response = request.execute(); String content = response.parseAsString(); //[END snippet] // Display the output XML. resp.setContentType("text/xml"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(resp.getOutputStream())); String formattedContent = content.replaceAll("(<ListBucketResult)", XSL + "$1"); writer.append(formattedContent); writer.flush(); resp.setStatus(200); } catch (Throwable e) { resp.sendError(404, e.getMessage()); } }
Example 9
Source File: TokenResponseException.java From google-oauth-java-client with Apache License 2.0 | 5 votes |
/** * 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: LookupControllerTest.java From reposilite with Apache License 2.0 | 4 votes |
static void assert404WithMessage(HttpResponse response, String message) throws IOException { assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); String content = response.parseAsString(); System.out.println(content); assertTrue(content.contains("REPOSILITE_MESSAGE = '" + message + "'")); }
Example 11
Source File: StorageServiceAccountSample.java From cloud-storage-docs-xml-api-examples with Apache License 2.0 | 4 votes |
public static void main(String[] args) { try { try { httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // Check for valid setup. Preconditions.checkArgument(!SERVICE_ACCOUNT_EMAIL.startsWith("[["), "Please enter your service account e-mail from the Google APIs " + "Console to the SERVICE_ACCOUNT_EMAIL constant in %s", StorageServiceAccountSample.class.getName()); Preconditions.checkArgument(!BUCKET_NAME.startsWith("[["), "Please enter your desired Google Cloud Storage bucket name " + "to the BUCKET_NAME constant in %s", StorageServiceAccountSample.class.getName()); String p12Content = Files.readFirstLine(new File("key.p12"), Charset.defaultCharset()); Preconditions.checkArgument(!p12Content.startsWith("Please"), p12Content); //[START snippet] // Build a service account credential. GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) .setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE)) .setServiceAccountPrivateKeyFromP12File(new File("key.p12")) .build(); // Set up and execute a Google Cloud Storage request. String URI = "https://storage.googleapis.com/" + BUCKET_NAME; HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential); GenericUrl url = new GenericUrl(URI); HttpRequest request = requestFactory.buildGetRequest(url); HttpResponse response = request.execute(); String content = response.parseAsString(); //[END snippet] // Instantiate transformer input. Source xmlInput = new StreamSource(new StringReader(content)); StreamResult xmlOutput = new StreamResult(new StringWriter()); // Configure transformer. Transformer transformer = TransformerFactory.newInstance().newTransformer(); // An identity // transformer transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(xmlInput, xmlOutput); // Pretty print the output XML. System.out.println("\nBucket listing for " + BUCKET_NAME + ":\n"); System.out.println(xmlOutput.getWriter().toString()); System.exit(0); } catch (IOException e) { System.err.println(e.getMessage()); } } catch (Throwable t) { t.printStackTrace(); } System.exit(1); }