private <T> T makeGetRequest(String url, Optional<Map<String, String>> parameters, Class<T> clazz) throws IOException { HttpRequestFactory requestFactory = httpTransport.createRequestFactory(); HttpRequest getRequest = requestFactory .buildGetRequest(new GenericUrl(url + "?" + generateParamsString(parameters))); 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); }
try { Insert req = storage.objects().insert(object.getBucket(), object); GenericUrl url = req.buildHttpRequest().getUrl(); String scheme = url.getScheme(); String host = url.getHost(); int port = url.getPort(); port = port > 0 ? port : url.toURL().getDefaultPort(); String path = "/upload" + url.getRawPath(); HttpRequestFactory requestFactory = storage.getRequestFactory(); HttpRequest httpRequest = requestFactory.buildPostRequest(url, new JsonHttpContent(jsonFactory, object)); HttpHeaders requestHeaders = httpRequest.getHeaders(); requestHeaders.set( "X-Upload-Content-Type", firstNonNull(object.getContentType(), "application/octet-stream")); HttpResponse response = httpRequest.execute(); if (response.getStatusCode() != 200) { GoogleJsonError error = new GoogleJsonError(); error.setCode(response.getStatusCode()); error.setMessage(response.getStatusMessage()); throw translate(error);
private static String getAppEngineProjectIdFromMetadataServer() throws IOException { String metadata = "http://metadata.google.internal"; String projectIdURL = "/computeMetadata/v1/project/project-id"; GenericUrl url = new GenericUrl(metadata + projectIdURL); HttpTransport netHttpTransport = new NetHttpTransport(); HttpRequestFactory requestFactory = netHttpTransport.createRequestFactory(); HttpRequest request = requestFactory .buildGetRequest(url) .setConnectTimeout(500) .setReadTimeout(500) .setHeaders(new HttpHeaders().set("Metadata-Flavor", "Google")); HttpResponse response = request.execute(); return headerContainsMetadataFlavor(response) ? response.parseAsString() : null; }
private String requestRaw(String path) throws IOException { HttpRequest getRequest = TRANSPORT.createRequestFactory().buildGetRequest( new GenericUrl(baseUrl + path)); HttpHeaders headers = new HttpHeaders(); headers.setAuthorization("Bearer " + accessToken); getRequest.setHeaders(headers); HttpResponse response = getRequest.execute(); validateResponse(getRequest, response, 200); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(response.getContent(), byteArrayOutputStream, true); return byteArrayOutputStream.toString(); }
private void delete(String url) { HttpHeaders headers = new HttpHeaders(); headers.setAccept("text/turtle"); headers.setCookie(authCookie); try { HttpRequest deleteRequest = factory.buildDeleteRequest(new GenericUrl(url)) .setThrowExceptionOnExecuteError(false); deleteRequest.setHeaders(headers); validateResponse(deleteRequest.execute(), 200); logger.debug("Deleted: {}", url); } catch (IOException e) { throw new IllegalStateException("Couldn't delete: " + url, e); } }
"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)); HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(); HttpRequest request = requestFactory.buildPostRequest(url, content); request.setParser(JSON_FACTORY.createJsonObjectParser()); request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH")); HttpResponse response = request.execute(); 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",
@Override protected TokenResponse executeRefreshToken() throws IOException { GenericUrl tokenUrl = new GenericUrl(getTokenServerEncodedUrl()); HttpRequest request = getTransport().createRequestFactory().buildGetRequest(tokenUrl); request.setParser(new JsonObjectParser(getJsonFactory())); request.getHeaders().set("Metadata-Flavor", "Google"); return request.execute().parseAs(TokenResponse.class); }
/** * 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"); }
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; } }
static <T> T makePostRequest(HttpTransport httpTransport, String url, HttpContent httpContent, Class<T> clazz) 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()); } String result = CharStreams .toString(new InputStreamReader(response.getContent(), Charsets.UTF_8)); return new ObjectMapper().readValue(result, clazz); } }
private HttpResponse getMetadataResponse(String url) throws IOException { GenericUrl genericUrl = new GenericUrl(url); HttpRequest request = transportFactory.create().createRequestFactory().buildGetRequest(genericUrl); JsonObjectParser parser = new JsonObjectParser(OAuth2Utils.JSON_FACTORY); request.setParser(parser); request.getHeaders().set("Metadata-Flavor", "Google"); request.setThrowExceptionOnExecuteError(false); HttpResponse response; try { response = request.execute(); } catch (UnknownHostException exception) { throw new IOException("ComputeEngineCredentials cannot find the metadata server. This is" + " likely because code is not running on Google Compute Engine.", exception); } return response; }
/** Posts a new status for the user, initially marked as private.**/ public void postStatus(String content, String idempotencyKey) throws IOException { ImmutableMap<String, String> formParams = ImmutableMap.of( "status", content, // Default everything to private to avoid a privacy incident "visibility", "private" ); UrlEncodedContent urlEncodedContent = new UrlEncodedContent(formParams); HttpRequest postRequest = TRANSPORT.createRequestFactory() .buildPostRequest( new GenericUrl(baseUrl + POST_URL), urlEncodedContent) .setThrowExceptionOnExecuteError(false); HttpHeaders headers = new HttpHeaders(); headers.setAuthorization("Bearer " + accessToken); if (!Strings.isNullOrEmpty(idempotencyKey)) { // This prevents the same post from being posted twice in the case of network errors headers.set("Idempotency-Key", idempotencyKey); } postRequest.setHeaders(headers); HttpResponse response = postRequest.execute(); validateResponse(postRequest, response, 200); }
@Override public String open(Job loadJob) { try { String builder = BASE_RESUMABLE_URI + options.getProjectId() + "/jobs"; GenericUrl url = new GenericUrl(builder); url.set("uploadType", "resumable"); JsonFactory jsonFactory = bigquery.getJsonFactory(); HttpRequestFactory requestFactory = bigquery.getRequestFactory(); HttpRequest httpRequest = requestFactory.buildPostRequest(url, new JsonHttpContent(jsonFactory, loadJob)); httpRequest.getHeaders().set("X-Upload-Content-Value", "application/octet-stream"); HttpResponse response = httpRequest.execute(); return response.getHeaders().getLocation(); } catch (IOException ex) { throw translate(ex); } }
/** Posts an RDF model to a Solid server. **/ public String postContent( String url, String slug, String type, Model model) throws IOException { StringWriter stringWriter = new StringWriter(); model.write(stringWriter, "TURTLE"); HttpContent content = new ByteArrayContent("text/turtle", stringWriter.toString().getBytes()); HttpRequest postRequest = factory.buildPostRequest( new GenericUrl(url), content); HttpHeaders headers = new HttpHeaders(); headers.setCookie(authCookie); headers.set("Link", "<" + type + ">; rel=\"type\""); headers.set("Slug", slug); postRequest.setHeaders(headers); HttpResponse response = postRequest.execute(); validateResponse(response, 201); return response.getHeaders().getLocation(); }
return null; GenericUrl url = new GenericUrl(uploadId); HttpRequest httpRequest = bigquery .getRequestFactory() .buildPutRequest(url, new ByteArrayContent(null, toWrite, toWriteOffset, length)); httpRequest.setParser(bigquery.getObjectParser()); long limit = destOffset + length; StringBuilder range = new StringBuilder("bytes "); range.append('*'); httpRequest.getHeaders().setContentRange(range.toString()); int code; String message; HttpResponse response = null; try { response = httpRequest.execute(); code = response.getStatusCode(); message = response.getStatusMessage(); } catch (HttpResponseException ex) { exception = ex; return last && response != null ? response.parseAs(Job.class) : null; } catch (IOException ex) { throw translate(ex);
String STORAGE_SCOPE = "https://www.googleapis.com/auth/devstorage.read_write"; JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); Log.d("testing", "checking if I can create a credential"); httpTransport = AndroidHttp.newCompatibleTransport(); KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(resources_.openRawResource(R.raw.gcs_privatekey), "password".toCharArray()); PrivateKey key = (PrivateKey) keystore.getKey("privatekey", "password".toCharArray()); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountPrivateKey(key) .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) .setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE)) // .setServiceAccountUser(SERVICE_ACCOUNT_EMAIL) // .setClientSecrets(CLIENT_ID, CLIENT_SECRET) .build(); credential.refreshToken(); 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(); Log.d("testing", "response content is: " + content); new Storage.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName("appname").build();
/** * Tests behavior when URL validation is disabled. */ @Test public void testUrlMismatch_verifyDisabled() throws IOException { MockResponse mockResponse = new MockResponse("test response"); mockResponse.setValidateUrlMatches(false); HttpRequest request = mockHttpServer .getHttpTransport() .createRequestFactory() .buildGetRequest( new GenericUrl("http://www.example.com/does_not_match_mock_http_server_url")); request.setContent(new ByteArrayContent("text", "test content".getBytes(UTF_8))); HttpHeaders headers = new HttpHeaders(); headers.set("one", "1"); headers.set("two", "2"); request.setHeaders(headers); mockHttpServer.setMockResponse(mockResponse); HttpResponse response = request.execute(); ActualResponse actualResponse = mockHttpServer.getLastResponse(); assertEquals("Incorrect response code", 200, response.getStatusCode()); assertEquals( "Request header 'one' incorrect", "1", actualResponse.getRequestHeader("one").get(0)); assertEquals( "Request header 'two' incorrect", "2", actualResponse.getRequestHeader("two").get(0)); }
protected InputStream getStream(String uri) throws APIException { HttpRequestFactory factory = getRequestFactory(); HttpRequest request; HttpResponse response; try { request = factory.buildGetRequest(new GenericUrl(apiURL + uri)); request.setConnectTimeout(clientConnectTimeout); request.setReadTimeout(clientRequestTimeout); request.setHeaders(getHttpHeaders()); response = request.execute(); if (!Arrays.asList(SC_OK, HttpStatus.SC_ACCEPTED, HttpStatus.SC_CREATED) .contains(response.getStatusCode())) { throw new APIException(response.getStatusCode(), String.format("Failed to execute api call: %s", uri)); } return response.getContent(); } catch (HttpResponseException ex) { throw getAPIException(ex); } catch (IOException ex) { throw new APIException(String .format("Failed to execute API call: %s. Reason: %s", uri, ex.getMessage()), ex); } }
new GenericUrl(UriTemplate.expand(api.getBaseUrl() + method.getPath(), param, true)); System.out.println(url); HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential); HttpRequest request = requestFactory.buildRequest(method.getHttpMethod(), url, content); String response = request.execute().parseAsString(); System.out.println(response);
return; GenericUrl url = new GenericUrl(uploadId); HttpRequest httpRequest = storage .getRequestFactory() .buildPutRequest(url, new ByteArrayContent(null, toWrite, toWriteOffset, length)); long limit = destOffset + length; StringBuilder range = new StringBuilder("bytes "); range.append('*'); httpRequest.getHeaders().setContentRange(range.toString()); int code; String message; HttpResponse response = null; try { response = httpRequest.execute(); code = response.getStatusCode(); message = response.getStatusMessage(); } catch (HttpResponseException ex) { exception = ex; } finally { if (response != null) { response.disconnect();