本文整理汇总了Java中com.google.api.client.http.HttpResponse类的典型用法代码示例。如果您正苦于以下问题:Java HttpResponse类的具体用法?Java HttpResponse怎么用?Java HttpResponse使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HttpResponse类属于com.google.api.client.http包,在下文中一共展示了HttpResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: deleteInstanceId
import com.google.api.client.http.HttpResponse; //导入依赖的package包/类
private Task<Void> deleteInstanceId(final String instanceId) {
checkArgument(!Strings.isNullOrEmpty(instanceId), "instance ID must not be null or empty");
return ImplFirebaseTrampolines.submitCallable(app, new Callable<Void>(){
@Override
public Void call() throws Exception {
String url = String.format(
"%s/project/%s/instanceId/%s", IID_SERVICE_URL, projectId, instanceId);
HttpRequest request = requestFactory.buildDeleteRequest(new GenericUrl(url));
request.setParser(new JsonObjectParser(jsonFactory));
request.setResponseInterceptor(interceptor);
HttpResponse response = null;
try {
response = request.execute();
ByteStreams.exhaust(response.getContent());
} catch (Exception e) {
handleError(instanceId, e);
} finally {
if (response != null) {
response.disconnect();
}
}
return null;
}
});
}
示例2: signInWithCustomToken
import com.google.api.client.http.HttpResponse; //导入依赖的package包/类
private String signInWithCustomToken(String customToken) throws IOException {
GenericUrl url = new GenericUrl(ID_TOOLKIT_URL + "?key="
+ IntegrationTestUtils.getApiKey());
Map<String, Object> content = ImmutableMap.<String, Object>of(
"token", customToken, "returnSecureToken", true);
HttpRequest request = transport.createRequestFactory().buildPostRequest(url,
new JsonHttpContent(jsonFactory, content));
request.setParser(new JsonObjectParser(jsonFactory));
HttpResponse response = request.execute();
try {
GenericJson json = response.parseAs(GenericJson.class);
return json.get("idToken").toString();
} finally {
response.disconnect();
}
}
示例3: getPublicKeysJson
import com.google.api.client.http.HttpResponse; //导入依赖的package包/类
/**
*
* @return
* @throws IOException
*/
private JsonObject getPublicKeysJson() throws IOException {
// get public keys
URI uri = URI.create(pubKeyUrl);
GenericUrl url = new GenericUrl(uri);
HttpTransport http = new NetHttpTransport();
HttpResponse response = http.createRequestFactory().buildGetRequest(url).execute();
// store json from request
String json = response.parseAsString();
// disconnect
response.disconnect();
// parse json to object
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
return jsonObject;
}
示例4: createThumbnail
import com.google.api.client.http.HttpResponse; //导入依赖的package包/类
/**
* Richiede ad Alfresco la creazione di una <i>thumbnail</i>.
* <p>
* Si tenga presente che in caso di creazione asincrona la <i>thumbnail</i> potrebbe non essere
* subito disponibile anche se il metodo ha restituito informazioni valide.
*
* @param pContentId
* L'id del contenuto.
* @param pThumbDefinition
* Il nome della <i>thumbnail</i> di cui si richiede la crezione.
* @param pAsync
* Se la crazione deve essere sincrona ({@code true} o asincrona ({@false}).
*
* @return La <i>thumbnail</i> richiesta o {@code null} se il tipo di <i>thumbnail</i> di cui si
* è richiesta la creazione non è valido per il contenuto specificato.
*
* @throws IOException
*/
public Thumbnail createThumbnail(String pContentId, String pThumbDefinition, boolean pAsync) throws IOException {
/*
* POST <base>/content{property}/thumbnails?as={async?}
*
* {
* "thumbnailName": <name>
* }
*/
GenericUrl lUrl = getContentUrl(pContentId);
lUrl.appendRawPath(URL_RELATIVE_THUMBNAILS);
lUrl.set("as", pAsync);
// Recupero delle definizioni valide
// Purtroppo Alfresco restituisce successo anche se viene richiesta la generazione di una
// thumbnail non possibile. Controllando preventivamente si può restituire null.
List<String> lThumbDefinitions = getThumbnailDefinitions(pContentId);
if (!lThumbDefinitions.contains(pThumbDefinition)) {
return null;
}
JsonHttpContent lContent = new JsonHttpContent(JSON_FACTORY, new Thumbnail(pThumbDefinition));
HttpHeaders lRequestHeaders = new HttpHeaders().setContentType("application/json");
HttpRequest lRequest =
mHttpRequestFactory.buildPostRequest(lUrl, lContent).setHeaders(lRequestHeaders);
HttpResponse lResponse = lRequest.execute();
Thumbnail lThumbnail = lResponse.parseAs(Thumbnail.class);
return lThumbnail;
}
示例5: initiateResumableUpload
import com.google.api.client.http.HttpResponse; //导入依赖的package包/类
/**
* Initiate a resumable upload direct to the cloud storage API. Providing an origin will enable
* CORS requests to the upload URL from the specified origin.
*
* @param bucket the cloud storage bucket to upload to
* @param name the name of the resource that will be uploaded
* @param contentType the resource's content/mime type
* @param origin the origin to allow for CORS requests
* @return the upload URL
* @see <a href="https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload">Performing a Resumable Upload</a>
*/
public String initiateResumableUpload(String bucket, String name, String contentType, String origin) {
String uploadUrl = String.format("%s/upload/storage/v1/b/%s/o", BASE_GOOGLE_API_URL, bucket);
GenericUrl url = new GenericUrl(uploadUrl);
url.put("uploadType", "resumable");
url.put("name", name);
HttpHeaders headers = new HttpHeaders();
headers.put("X-Upload-Content-Type", contentType);
if (origin != null) {
headers.put("Origin", origin); // Add origin header for CORS support
}
HttpResponse response;
try {
response = httpRequestFactory
.buildPostRequest(url, null)
.setHeaders(headers)
.execute();
} catch (IOException e) {
throw new GoogleCloudStorageException(e, "Cannot initiate upload: %s", e.getMessage());
}
return response.getHeaders().getLocation();
}
示例6: registerMetric_fetchesStackdriverDefinition
import com.google.api.client.http.HttpResponse; //导入依赖的package包/类
@Test
public void registerMetric_fetchesStackdriverDefinition() throws Exception {
// Stackdriver throws an Exception with the status message "ALREADY_EXISTS" when you try to
// register a metric that's already been registered, so we fake one here.
ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream);
HttpResponseException.Builder httpResponseExceptionBuilder =
new HttpResponseException.Builder(response);
httpResponseExceptionBuilder.setStatusCode(400);
httpResponseExceptionBuilder.setStatusMessage("ALREADY_EXISTS");
GoogleJsonResponseException exception =
new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
when(metricDescriptorCreate.execute()).thenThrow(exception);
StackdriverWriter writer =
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
writer.registerMetric(metric);
verify(client.projects().metricDescriptors().get("metric")).execute();
}
示例7: registerMetric_rethrowsException
import com.google.api.client.http.HttpResponse; //导入依赖的package包/类
@Test
public void registerMetric_rethrowsException() throws Exception {
ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream);
HttpResponseException.Builder httpResponseExceptionBuilder =
new HttpResponseException.Builder(response);
httpResponseExceptionBuilder.setStatusCode(404);
GoogleJsonResponseException exception =
new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
when(metricDescriptorCreate.execute()).thenThrow(exception);
StackdriverWriter writer =
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
assertThrows(GoogleJsonResponseException.class, () -> writer.registerMetric(metric));
assertThat(exception.getStatusCode()).isEqualTo(404);
}
示例8: getEncodedTimeSeries_nullLabels_encodes
import com.google.api.client.http.HttpResponse; //导入依赖的package包/类
@Test
public void getEncodedTimeSeries_nullLabels_encodes() throws Exception {
ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream);
HttpResponseException.Builder httpResponseExceptionBuilder =
new HttpResponseException.Builder(response);
httpResponseExceptionBuilder.setStatusCode(400);
httpResponseExceptionBuilder.setStatusMessage("ALREADY_EXISTS");
GoogleJsonResponseException exception =
new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
when(metricDescriptorCreate.execute()).thenThrow(exception);
when(metricDescriptorGet.execute())
.thenReturn(new MetricDescriptor().setName("foo").setLabels(null));
StackdriverWriter writer =
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
writer.registerMetric(metric);
TimeSeries timeSeries =
writer.getEncodedTimeSeries(
MetricPoint.create(metric, ImmutableList.of("foo"), Instant.ofEpochMilli(1337), 10L));
assertThat(timeSeries.getMetric().getLabels()).isEmpty();
}
示例9: testSimpleRetry
import com.google.api.client.http.HttpResponse; //导入依赖的package包/类
public void testSimpleRetry() throws Exception {
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 3);
MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder()
.build();
MockSleeper mockSleeper = new MockSleeper();
RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper,
TimeValue.timeValueSeconds(5));
Compute client = new Compute.Builder(fakeTransport, new JacksonFactory(), null)
.setHttpRequestInitializer(retryHttpInitializerWrapper)
.setApplicationName("test")
.build();
HttpRequest request = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
HttpResponse response = request.execute();
assertThat(mockSleeper.getCount(), equalTo(3));
assertThat(response.getStatusCode(), equalTo(200));
}
示例10: testIOExceptionRetry
import com.google.api.client.http.HttpResponse; //导入依赖的package包/类
public void testIOExceptionRetry() throws Exception {
FailThenSuccessBackoffTransport fakeTransport =
new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 1, true);
MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder()
.build();
MockSleeper mockSleeper = new MockSleeper();
RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper,
TimeValue.timeValueMillis(500));
Compute client = new Compute.Builder(fakeTransport, new JacksonFactory(), null)
.setHttpRequestInitializer(retryHttpInitializerWrapper)
.setApplicationName("test")
.build();
HttpRequest request = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
HttpResponse response = request.execute();
assertThat(mockSleeper.getCount(), equalTo(1));
assertThat(response.getStatusCode(), equalTo(200));
}
示例11: getInputStream
import com.google.api.client.http.HttpResponse; //导入依赖的package包/类
protected ByteArrayInputStream getInputStream(String endPoint,
Date modifiedAfter,
Map<String, String> params,
String accept) throws IOException {
OAuthRequestResource req = new OAuthRequestResource(config, signerFactory, endPoint, "GET", null, params, accept);
req.setToken(token);
req.setTokenSecret(tokenSecret);
if (modifiedAfter != null) {
req.setIfModifiedSince(modifiedAfter);
}
try {
HttpResponse resp = req.execute();
InputStream is = resp.getContent();
byte[] bytes = IOUtils.toByteArray(is);
is.close();
return new ByteArrayInputStream(bytes);
} catch (IOException ioe) {
throw convertException(ioe);
}
}
示例12: delete
import com.google.api.client.http.HttpResponse; //导入依赖的package包/类
protected Response delete(String endPoint) throws IOException {
HttpResponse resp = null;
OAuthRequestResource req = new OAuthRequestResource(config, signerFactory, endPoint, "DELETE", null, null);
req.setToken(token);
req.setTokenSecret(tokenSecret);
try {
resp = req.execute();
// No-Content Returned from Xero API
if (resp.getStatusCode() == 204) {
return unmarshallResponse("<Response><Status>DELETED</Status></Response>", Response.class);
}
return unmarshallResponse(resp.parseAsString(), Response.class);
} catch (IOException ioe) {
throw xeroExceptionHandler.convertException(ioe);
}
}
示例13: sendPostMultipart
import com.google.api.client.http.HttpResponse; //导入依赖的package包/类
public static int sendPostMultipart(String urlString, Map<String, String> parameters)
throws IOException {
MultipartContent postBody = new MultipartContent()
.setMediaType(new HttpMediaType("multipart/form-data"));
postBody.setBoundary(MULTIPART_BOUNDARY);
for (Map.Entry<String, String> entry : parameters.entrySet()) {
HttpContent partContent = ByteArrayContent.fromString( // uses UTF-8 internally
null /* part Content-Type */, entry.getValue());
HttpHeaders partHeaders = new HttpHeaders()
.set("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\"");
postBody.addPart(new MultipartContent.Part(partHeaders, partContent));
}
GenericUrl url = new GenericUrl(new URL(urlString));
HttpRequest request = transport.createRequestFactory().buildPostRequest(url, postBody);
request.setHeaders(new HttpHeaders().setUserAgent(CloudToolsInfo.USER_AGENT));
request.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MS);
request.setReadTimeout(DEFAULT_READ_TIMEOUT_MS);
HttpResponse response = request.execute();
return response.getStatusCode();
}
示例14: testErrorCodeForbidden
import com.google.api.client.http.HttpResponse; //导入依赖的package包/类
/**
* Tests that a non-retriable error is not retried.
*/
@Test
public void testErrorCodeForbidden() throws IOException {
when(mockLowLevelRequest.execute())
.thenReturn(mockLowLevelResponse);
when(mockLowLevelResponse.getStatusCode())
.thenReturn(403) // Non-retryable error.
.thenReturn(200); // Shouldn't happen.
try {
Storage.Buckets.Get result = storage.buckets().get("test");
HttpResponse response = result.executeUnparsed();
assertNotNull(response);
} catch (HttpResponseException e) {
assertThat(e.getMessage(), Matchers.containsString("403"));
}
verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class));
verify(mockLowLevelRequest, atLeastOnce())
.addHeader(anyString(), anyString());
verify(mockLowLevelRequest).setTimeout(anyInt(), anyInt());
verify(mockLowLevelRequest).execute();
verify(mockLowLevelResponse).getStatusCode();
expectedLogs.verifyWarn("Request failed with code 403");
}
示例15: testBasicOperation
import com.google.api.client.http.HttpResponse; //导入依赖的package包/类
@Test
public void testBasicOperation() throws IOException {
when(mockLowLevelRequest.execute())
.thenReturn(mockLowLevelResponse);
when(mockLowLevelResponse.getStatusCode())
.thenReturn(200);
Storage.Buckets.Get result = storage.buckets().get("test");
HttpResponse response = result.executeUnparsed();
assertNotNull(response);
verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class));
verify(mockLowLevelRequest, atLeastOnce())
.addHeader(anyString(), anyString());
verify(mockLowLevelRequest).setTimeout(anyInt(), anyInt());
verify(mockLowLevelRequest).execute();
verify(mockLowLevelResponse).getStatusCode();
expectedLogs.verifyNotLogged("Request failed");
}