本文整理匯總了Java中com.google.api.client.http.HttpRequest.execute方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpRequest.execute方法的具體用法?Java HttpRequest.execute怎麽用?Java HttpRequest.execute使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類com.google.api.client.http.HttpRequest
的用法示例。
在下文中一共展示了HttpRequest.execute方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: signInWithCustomToken
import com.google.api.client.http.HttpRequest; //導入方法依賴的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();
}
}
示例2: testSimpleRetry
import com.google.api.client.http.HttpRequest; //導入方法依賴的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));
}
示例3: testIOExceptionRetry
import com.google.api.client.http.HttpRequest; //導入方法依賴的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));
}
示例4: hasMetadataServer
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
private static boolean hasMetadataServer(HttpTransport transport) {
try {
HttpRequest request = transport.createRequestFactory()
.buildGetRequest(new GenericUrl(METADATA_SERVER_URL));
HttpResponse response = request.execute();
HttpHeaders headers = response.getHeaders();
return "Google".equals(headers.getFirstHeaderStringValue("Metadata-Flavor"));
} catch (IOException | RuntimeException expected) {
// If an error happens, it's probably safe to say the metadata service isn't available where
// the code is running. We have to catch ApiProxyException due to the new dev server returning
// a different error for unresolvable hostnames. Due to not wanting to put a required
// dependency on the App Engine SDK here, we catch the generic RuntimeException and do a
// class name check.
if (expected instanceof RuntimeException
&& !API_PROXY_EXCEPTION_CLASS_NAME.equals(expected.getClass().getName())
&& !REMOTE_API_EXCEPTION_CLASS_NAME.equals(expected.getClass().getName())) {
throw (RuntimeException) expected;
}
}
return false;
}
示例5: sendPostMultipart
import com.google.api.client.http.HttpRequest; //導入方法依賴的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();
}
示例6: post
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
@SuppressWarnings("unchecked")
@Override
public <T> T post(String path, Object request, Type responseType)
throws RepoException, ValidationException {
HttpRequestFactory requestFactory = getHttpRequestFactory(getCredentials());
GenericUrl url = new GenericUrl(URI.create(API_URL + "/" + path));
try {
HttpRequest httpRequest = requestFactory.buildPostRequest(url,
new JsonHttpContent(JSON_FACTORY, request));
HttpResponse response = httpRequest.execute();
return (T) response.parseAs(responseType);
} catch (IOException e) {
throw new RepoException("Error running GitHub API operation " + path, e);
}
}
示例7: get
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
public String get(String url) {
try {
HttpRequest request = new NetHttpTransport()
.createRequestFactory()
.buildGetRequest(new GenericUrl(url));
HttpResponse response = request.execute();
InputStream is = response.getContent();
StringBuilder sb = new StringBuilder();
int ch;
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
response.disconnect();
return sb.toString();
} catch (Exception e) {
throw new RuntimeException();
}
}
示例8: getClientEmail
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
public static String getClientEmail(String accessToken) throws IOException {
/*
* Get loggined user info as described in
* https://developers.google.com/accounts/docs/OAuth2Login#userinfocall
*/
GenericUrl url = new GenericUrl("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken);
HttpRequest request = HTTP_REQUEST_FACTORY.buildGetRequest(url);
HttpResponse response = request.execute();
if (!response.isSuccessStatusCode()) {
throw new IOException(response.getStatusMessage());
}
JsonElement jsonElement = new JsonParser().parse(new InputStreamReader(response.getContent(), "utf-8"));
JsonObject jsonObj = jsonElement.getAsJsonObject();
return jsonObj.get("email").getAsString();
}
示例9: download
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
/**
* <p>Downloads and returns the stream of the
* input file associated to the given problem
* <tt>input</tt>.</p>
*
* @param input Input to download file from.
* @param attempt Attempt number.
* @return Stream to read which contains our downloaded file data.
* @throws IOException If any error occurs while downloading the file.
*/
public InputStream download(final ProblemInput input, final int attempt) throws IOException {
final String filename = buildFilename(input, attempt);
final StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(round.getURL())
.append(DO)
.append(COMMAND_PARAMETER)
.append(DOWNLOAD_COMMAND)
.append(PROBLEM_PARAMETER)
.append(input.getProblem().getId())
.append(FILENAME_PARAMETER)
.append(filename)
.append(INPUT_ID_PARAMETER)
.append(input.getNumber())
.append(CSRF_PARAMETER)
.append(values.getURLEncodedToken())
.append(AGENT_PARAMETER)
.append(DEFAULT_AGENT);
final HttpRequest request = executor.getRequest(urlBuilder.toString());
final HttpResponse response = request.execute();
return response.getContent();
}
示例10: getGoogleIdToken
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
private static String getGoogleIdToken(String jwt) throws Exception {
final GenericData tokenRequest =
new GenericData().set("grant_type", JWT_BEARER_TOKEN_GRANT_TYPE).set("assertion", jwt);
final UrlEncodedContent content = new UrlEncodedContent(tokenRequest);
final HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
final HttpRequest request =
requestFactory
.buildPostRequest(new GenericUrl(OAUTH_TOKEN_URI), content)
.setParser(new JsonObjectParser(JacksonFactory.getDefaultInstance()));
HttpResponse response;
String idToken = null;
response = request.execute();
GenericData responseData = response.parseAs(GenericData.class);
idToken = (String) responseData.get("id_token");
return idToken;
}
示例11: testGenerateAndVerifyIapRequestIsSuccessful
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
@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);
}
示例12: listBucket
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
/**
* 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.
GoogleCredential credential = GoogleCredential.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(
credential);
GenericUrl url = new GenericUrl(uri);
HttpRequest request = requestFactory.buildGetRequest(url);
HttpResponse response = request.execute();
String content = response.parseAsString();
//[END snippet]
return content;
}
示例13: execute
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
private <U, T extends ResponseEnvelope<U>> U execute(final HttpRequest httpRequest, final Class<T> responseType) throws IOException {
httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()));
if (authToken != null) {
HttpHeaders headers = httpRequest.getHeaders();
headers.set("X-Auth-Token", authToken);
}
HttpResponse httpResponse = httpRequest.execute();
T response = httpResponse.parseAs(responseType);
// Update authToken, if necessary
if (response.getAuthToken() != null) {
authToken = response.getAuthToken();
}
return response.getData();
}
示例14: download
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
public void download(int projectID, int fileID) throws IOException {
GenericUrl projectURL = new GenericUrl("http://minecraft.curseforge.com/projects/" + projectID);
HttpRequest projectRequest = requestFactory.buildGetRequest(projectURL);
// This will redirect - the point of this is just to obtain the new URL!
HttpResponse projectResponse = projectRequest.execute();
projectResponse.disconnect();
GenericUrl newURL = projectResponse.getRequest().getUrl();
newURL.appendRawPath("/files/" + fileID + "/download");
try {
download(newURL);
} catch (HttpResponseException e) {
// TODO Return this, instead of only logging
log("FAILED to download "+ newURL + "; you should manually download another version of this mod from " + projectURL);
}
}
示例15: create
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
public boolean create(String name, String rules) throws VaultException {
Map<String, Object> data = new HashMap<>();
data.put("rules", rules);
HttpContent content = new JsonHttpContent(getJsonFactory(), data);
try {
HttpRequest request = getRequestFactory().buildRequest(
"POST",
new GenericUrl(getConf().getAddress() + "/v1/sys/policy/" + name),
content
);
HttpResponse response = request.execute();
if (!response.isSuccessStatusCode()) {
LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
}
return response.isSuccessStatusCode();
} catch (IOException e) {
LOG.error(e.toString(), e);
throw new VaultException("Failed to authenticate: " + e.toString(), e);
}
}