本文整理了Java中com.google.api.client.http.HttpResponse
类的一些代码示例,展示了HttpResponse
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpResponse
类的具体详情如下:
包路径:com.google.api.client.http.HttpResponse
类名称:HttpResponse
暂无
代码示例来源:origin: google/data-transfer-project
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);
}
代码示例来源:origin: googleapis/google-cloud-java
@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);
}
}
代码示例来源:origin: googleapis/google-cloud-java
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;
}
代码示例来源:origin: google/data-transfer-project
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());
}
}
代码示例来源:origin: google/data-transfer-project
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());
}
}
代码示例来源:origin: google/data-transfer-project
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);
}
}
代码示例来源:origin: stackoverflow.com
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();
代码示例来源:origin: com.onpositive.aml/org.aml.registry
public static void readToFile(String url,File target) throws IOException {
HttpRequest buildGetRequest;
buildGetRequest = createRequestFactory.buildGetRequest(new GenericUrl(url));
InputStream str=buildGetRequest.execute().getContent();
FileUtils.copyInputStreamToFile(str, target);
}
代码示例来源:origin: GoogleCloudPlatform/java-docs-samples
"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",
代码示例来源:origin: com.google.api-client/google-api-client
@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);
}
代码示例来源:origin: google/data-transfer-project
/**
* 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");
}
代码示例来源:origin: google/data-transfer-project
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;
}
}
代码示例来源:origin: googleapis/google-cloud-java
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();
BaseEncoding base64 = BaseEncoding.base64();
HashFunction hashFunction = Hashing.sha256();
requestHeaders.set("x-goog-encryption-algorithm", "AES256");
requestHeaders.set("x-goog-encryption-key", key);
base64.encode(hashFunction.hashBytes(base64.decode(key)).asBytes()));
HttpResponse response = httpRequest.execute();
if (response.getStatusCode() != 200) {
GoogleJsonError error = new GoogleJsonError();
error.setCode(response.getStatusCode());
error.setMessage(response.getStatusMessage());
throw translate(error);
return response.getHeaders().getLocation();
} catch (IOException ex) {
span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage()));
代码示例来源:origin: com.google.api-client/google-api-client
static boolean runningOnComputeEngine(HttpTransport transport,
SystemEnvironmentProvider environment) {
// If the environment has requested that we do no GCE checks, return immediately.
if (Boolean.parseBoolean(environment.getEnv("NO_GCE_CHECK"))) {
return false;
}
GenericUrl tokenUrl = new GenericUrl(getMetadataServerUrl(environment));
for (int i = 1; i <= MAX_COMPUTE_PING_TRIES; ++i) {
try {
HttpRequest request = transport.createRequestFactory().buildGetRequest(tokenUrl);
request.setConnectTimeout(COMPUTE_PING_CONNECTION_TIMEOUT_MS);
HttpResponse response = request.execute();
try {
HttpHeaders headers = response.getHeaders();
return headersContainValue(headers, "Metadata-Flavor", "Google");
} finally {
response.disconnect();
}
} catch (SocketTimeoutException expected) {
// Ignore logging timeouts which is the expected failure mode in non GCE environments.
} catch (IOException e) {
LOGGER.log(
Level.WARNING,
"Failed to detect whether we are running on Google Compute Engine.",
e);
}
}
return false;
}
代码示例来源:origin: google/data-transfer-project
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();
}
代码示例来源:origin: firebase/firebase-admin-java
HttpRequestFactory requestFactory = options.getHttpTransport().createRequestFactory(
new FirebaseRequestInitializer(firebaseApp));
JsonFactory jsonFactory = options.getJsonFactory();
HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(METADATA_SERVICE_URL));
request.getHeaders().set("Metadata-Flavor", "Google");
HttpResponse response = request.execute();
try {
byte[] output = ByteStreams.toByteArray(response.getContent());
serviceAccountId = StringUtils.newStringUtf8(output).trim();
return new IAMCryptoSigner(requestFactory, jsonFactory, serviceAccountId);
} finally {
response.disconnect();
代码示例来源:origin: googleapis/google-cloud-java
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);
代码示例来源:origin: google/data-transfer-project
/** 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();
}
代码示例来源:origin: GoogleCloudPlatform/java-docs-samples
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);
代码示例来源:origin: GoogleCloudPlatform/google-cloud-datastore
@Nullable
private static String queryProjectIdFromComputeEngine() {
HttpTransport transport;
try {
transport = newTransport();
} catch (GeneralSecurityException | IOException e) {
logger.log(Level.WARNING, "Failed to create HttpTransport.", e);
return null;
}
try {
GenericUrl projectIdUrl =
new GenericUrl("http://metadata/computeMetadata/v1/project/project-id");
HttpRequest request = transport.createRequestFactory().buildGetRequest(projectIdUrl);
request.getHeaders().set("Metadata-Flavor", "Google");
String result = request.execute().parseAsString();
projectIdFromComputeEngine.set(result);
return result;
} catch (IOException e) {
logger.log(Level.INFO, "Could not determine project ID from Compute Engine.", e);
return null;
}
}
内容来源于网络,如有侵权,请联系作者删除!