下面列出了怎么用com.google.api.client.http.HttpRequestFactory的API类实例代码及写法,或者点击链接到github查看源代码。
private String loginAndGetId(HttpRequestFactory requestFactory, String tld) throws IOException {
logger.atInfo().log("Logging in to MoSAPI");
HttpRequest request =
requestFactory.buildGetRequest(new GenericUrl(String.format(LOGIN_URL, tld)));
request.getHeaders().setBasicAuthentication(String.format("%s_ry", tld), password);
HttpResponse response = request.execute();
Optional<HttpCookie> idCookie =
response.getHeaders().getHeaderStringValues("Set-Cookie").stream()
.flatMap(value -> HttpCookie.parse(value).stream())
.filter(cookie -> cookie.getName().equals(COOKIE_ID))
.findAny();
checkState(
idCookie.isPresent(),
"Didn't get the ID cookie from the login response. Code: %s, headers: %s",
response.getStatusCode(),
response.getHeaders());
return idCookie.get().getValue();
}
private <T extends RememberTheMilkResponse> T makeRequest(
Map<String, String> parameters, Class<T> dataClass) throws IOException {
URL signedUrl = signatureGenerator.getSignature(BASE_URL, parameters);
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
HttpRequest getRequest = requestFactory.buildGetRequest(new GenericUrl(signedUrl));
HttpResponse response = getRequest.execute();
int statusCode = response.getStatusCode();
if (statusCode != 200) {
throw new IOException(
"Bad status code: " + statusCode + " error: " + response.getStatusMessage());
}
T parsedResponse = xmlMapper.readValue(response.getContent(), dataClass);
if (parsedResponse.error != null) {
throw new IOException(
"Error making call to " + signedUrl + " error: " + parsedResponse.error);
}
return parsedResponse;
}
private <T> T makeGetRequest(String url, Optional<Map<String, String>> parameters, Class<T> clazz)
throws IOException, InvalidTokenException, PermissionDeniedException {
HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
HttpRequest getRequest =
requestFactory.buildGetRequest(
new GenericUrl(url + "?" + generateParamsString(parameters)));
HttpResponse response;
try {
response = getRequest.execute();
} catch (HttpResponseException e) {
response =
handleHttpResponseException(
() ->
requestFactory.buildGetRequest(
new GenericUrl(url + "?" + generateParamsString(parameters))),
e);
}
Preconditions.checkState(response.getStatusCode() == 200);
String result =
CharStreams.toString(new InputStreamReader(response.getContent(), Charsets.UTF_8));
return objectMapper.readValue(result, clazz);
}
public static String getAccessToken(String email, KeyStore pks) throws Exception {
PrivateKey pk = getPrivateKey(pks);
if (pk != null && !email.equals("")) {
try {
GoogleCredential credential = new GoogleCredential.Builder().setTransport(GoogleSpreadsheet.HTTP_TRANSPORT)
.setJsonFactory(GoogleSpreadsheet.JSON_FACTORY).setServiceAccountScopes(GoogleSpreadsheet.SCOPES).setServiceAccountId(email)
.setServiceAccountPrivateKey(pk).build();
HttpRequestFactory requestFactory = GoogleSpreadsheet.HTTP_TRANSPORT.createRequestFactory(credential);
GenericUrl url = new GenericUrl(GoogleSpreadsheet.getSpreadsheetFeedURL().toString());
HttpRequest request = requestFactory.buildGetRequest(url);
request.execute();
return credential.getAccessToken();
} catch (Exception e) {
throw new Exception("Error fetching Access Token", e);
}
}
return null;
}
private <T> T makeRequest(String url, Class<T> clazz, TokensAndUrlAuthData authData)
throws IOException {
HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
HttpRequest getRequest =
requestFactory.buildGetRequest(
new GenericUrl(url + "?access_token=" + authData.getAccessToken()));
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);
}
/**
* 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;
}
private void subtestRefreshToken_request(AccessTokenTransport transport, int expectedCalls)
throws Exception {
Credential credential =
new Credential.Builder(BearerToken.queryParameterAccessMethod()).setTransport(transport)
.setJsonFactory(JSON_FACTORY)
.setTokenServerUrl(TOKEN_SERVER_URL)
.setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET))
.build()
.setRefreshToken(REFRESH_TOKEN)
.setAccessToken(ACCESS_TOKEN);
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
HttpRequest request = requestFactory.buildDeleteRequest(HttpTesting.SIMPLE_GENERIC_URL);
request.setThrowExceptionOnExecuteError(false);
request.execute();
assertEquals(expectedCalls, transport.calls);
}
/**
* This methods is adds a document that exists in Mendeley to a specific folder
* via the POST https://api.mendeley.com/folders/{id}/documents endpoint.
* @param document This methods needs a dkocument to add
* @param folder_id This passes the folder where to document is added to
*/
public void addDocumentToFolder(MendeleyDocument document, String folder_id){
refreshTokenIfNecessary();
HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
HttpRequest request;
HttpRequest patch_request;
Gson gson = new GsonBuilder().create();
String json_body = "{\"id\": \""+ document.getId() + "\" }";
String resource_url = "https://api.mendeley.com/folders/"+ folder_id + "/documents";
GenericUrl gen_url = new GenericUrl(resource_url);
try {
final HttpContent content = new ByteArrayContent("application/json", json_body.getBytes("UTF8") );
patch_request = requestFactory.buildPostRequest(gen_url, content);
patch_request.getHeaders().setAuthorization("Bearer " + access_token);
patch_request.getHeaders().setContentType("application/vnd.mendeley-document.1+json");
String rawResponse = patch_request.execute().parseAsString();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testHttpRetries() throws Exception {
List<MockLowLevelHttpResponse> mockResponses = ImmutableList.of(
firstRpcResponse.setStatusCode(503).setContent("{}"),
new MockLowLevelHttpResponse().setContent("{}"));
MockHttpTransport transport = new MultiRequestMockHttpTransport(mockResponses);
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(new MockGoogleCredentials("test-token"))
.setProjectId(PROJECT_ID)
.setHttpTransport(transport)
.build();
FirebaseApp app = FirebaseApp.initializeApp(options);
HttpRequestFactory requestFactory = TestApiClientUtils.delayBypassedRequestFactory(app);
FirebaseProjectManagementServiceImpl serviceImpl = new FirebaseProjectManagementServiceImpl(
app, new MockSleeper(), new MockScheduler(), requestFactory);
serviceImpl.setInterceptor(interceptor);
serviceImpl.deleteShaCertificate(SHA1_RESOURCE_NAME);
String expectedUrl = String.format(
"%s/v1beta1/%s", FIREBASE_PROJECT_MANAGEMENT_URL, SHA1_RESOURCE_NAME);
checkRequestHeader(expectedUrl, HttpMethod.DELETE);
}
private static FirebaseProjectManagementServiceImpl initServiceImpl(
List<MockLowLevelHttpResponse> mockResponses,
MultiRequestTestResponseInterceptor interceptor) {
MockHttpTransport transport = new MultiRequestMockHttpTransport(mockResponses);
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(new MockGoogleCredentials("test-token"))
.setProjectId(PROJECT_ID)
.setHttpTransport(transport)
.build();
FirebaseApp app = FirebaseApp.initializeApp(options);
HttpRequestFactory requestFactory = TestApiClientUtils.retryDisabledRequestFactory(app);
FirebaseProjectManagementServiceImpl serviceImpl = new FirebaseProjectManagementServiceImpl(
app, new MockSleeper(), new MockScheduler(), requestFactory);
serviceImpl.setInterceptor(interceptor);
return serviceImpl;
}
/**
* Checks whther the given HttpRequestFactory has been configured for authorization and
* automatic retries.
*
* @param requestFactory The HttpRequestFactory to check.
*/
public static void assertAuthAndRetrySupport(HttpRequestFactory requestFactory) {
assertTrue(requestFactory.getInitializer() instanceof FirebaseRequestInitializer);
HttpRequest request;
try {
request = requestFactory.buildGetRequest(TEST_URL);
} catch (IOException e) {
throw new RuntimeException("Failed to initialize request", e);
}
// Verify authorization
assertTrue(request.getHeaders().getAuthorization().startsWith("Bearer "));
// Verify retry support
HttpUnsuccessfulResponseHandler retryHandler = request.getUnsuccessfulResponseHandler();
assertTrue(retryHandler instanceof RetryHandlerDecorator);
RetryConfig retryConfig = ((RetryHandlerDecorator) retryHandler).getRetryHandler()
.getRetryConfig();
assertEquals(DEFAULT_RETRY_CONFIG.getMaxRetries(), retryConfig.getMaxRetries());
assertEquals(DEFAULT_RETRY_CONFIG.getMaxIntervalMillis(), retryConfig.getMaxIntervalMillis());
assertFalse(retryConfig.isRetryOnIOExceptions());
assertEquals(DEFAULT_RETRY_CONFIG.getRetryStatusCodes(), retryConfig.getRetryStatusCodes());
}
public ApiClient(
String basePath,
HttpTransport transport,
HttpRequestInitializer initializer,
ObjectMapper objectMapper,
HttpRequestFactory reqFactory
) {
this.basePath = basePath == null ? defaultBasePath : (
basePath.endsWith("/") ? basePath.substring(0, basePath.length() - 1) : basePath
);
if (transport != null) {
this.httpTransport = transport;
}
this.httpRequestFactory = (reqFactory != null ? reqFactory : (transport == null ? Utils.getDefaultTransport() : transport).createRequestFactory(initializer) );
this.objectMapper = (objectMapper == null ? createDefaultObjectMapper() : objectMapper);
}
/**
* Specifying both credential and transport, the factory will use the
* transport specified and not the one in the credential.
*/
@Test
public void makeClient_WithCredentialTransport() {
NetHttpTransport credTransport = new NetHttpTransport();
NetHttpTransport transport = new NetHttpTransport();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(credTransport)
.build();
DatastoreOptions options = new DatastoreOptions.Builder()
.projectId(PROJECT_ID)
.credential(credential)
.transport(transport)
.build();
HttpRequestFactory f = factory.makeClient(options);
assertNotSame(credTransport, f.getTransport());
assertEquals(transport, f.getTransport());
}
@Inject
public DicomWebClient(
HttpRequestFactory requestFactory,
@Annotations.DicomwebAddr String serviceUrlPrefix,
String stowPath) {
this.requestFactory = requestFactory;
this.serviceUrlPrefix = StringUtil.trim(serviceUrlPrefix);
this.stowPath = stowPath;
DicomWebValidation.validatePath(this.serviceUrlPrefix, DicomWebValidation.DICOMWEB_ROOT_VALIDATION);
}
/**
* Gets the report HTTP URL connection given report URL and proper information needed to
* authenticate the request.
*
* @param reportUrl the URL of the report response or download
* @return the report HTTP URL connection
* @throws AuthenticationException If OAuth authorization fails.
*/
@VisibleForTesting
HttpRequestFactory getHttpRequestFactory(final String reportUrl, String version)
throws AuthenticationException {
final HttpHeaders httpHeaders = createHeaders(reportUrl, version);
return httpTransport.createRequestFactory(
request -> {
request.setHeaders(httpHeaders);
request.setConnectTimeout(reportDownloadTimeout);
request.setReadTimeout(reportDownloadTimeout);
request.setThrowExceptionOnExecuteError(false);
request.setLoggingEnabled(true);
request.setResponseInterceptor(responseInterceptor);
});
}
public HttpResponse createProjectForHttpResponse(String accessToken, String xeroTenantId, ProjectCreateOrUpdate projectCreateOrUpdate) throws IOException {
// verify the required parameter 'xeroTenantId' is set
if (xeroTenantId == null) {
throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createProject");
}// verify the required parameter 'projectCreateOrUpdate' is set
if (projectCreateOrUpdate == null) {
throw new IllegalArgumentException("Missing the required parameter 'projectCreateOrUpdate' when calling createProject");
}
if (accessToken == null) {
throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createProject");
}
HttpHeaders headers = new HttpHeaders();
headers.set("Xero-Tenant-Id", xeroTenantId);
headers.setAccept("application/json");
headers.setUserAgent(this.getUserAgent());
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects");
String url = uriBuilder.build().toString();
GenericUrl genericUrl = new GenericUrl(url);
if (logger.isDebugEnabled()) {
logger.debug("POST " + genericUrl.toString());
}
HttpContent content = null;
content = apiClient.new JacksonJsonHttpContent(projectCreateOrUpdate);
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
HttpTransport transport = apiClient.getHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
return requestFactory.buildRequest(HttpMethods.POST, genericUrl, content).setHeaders(headers)
.setConnectTimeout(apiClient.getConnectionTimeout())
.setReadTimeout(apiClient.getReadTimeout()).execute();
}
public static void main(final String[] args) throws Exception {
final HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
final HttpRequest request = requestFactory.buildGetRequest(new GenericUrl("https://www.google.com"));
final int statusCode = request.execute().getStatusCode();
if (200 != statusCode)
throw new AssertionError("ERROR: response: " + statusCode);
TestUtil.checkSpan(new ComponentSpanCount("google-http-client", 1));
}
static String makeRawPostRequest(HttpTransport httpTransport, String url, HttpContent httpContent)
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());
}
return CharStreams
.toString(new InputStreamReader(response.getContent(), Charsets.UTF_8));
}
public HttpResponse updateProjectForHttpResponse(String accessToken, String xeroTenantId, UUID projectId, ProjectCreateOrUpdate projectCreateOrUpdate) throws IOException {
// verify the required parameter 'xeroTenantId' is set
if (xeroTenantId == null) {
throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling updateProject");
}// verify the required parameter 'projectId' is set
if (projectId == null) {
throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling updateProject");
}// verify the required parameter 'projectCreateOrUpdate' is set
if (projectCreateOrUpdate == null) {
throw new IllegalArgumentException("Missing the required parameter 'projectCreateOrUpdate' when calling updateProject");
}
if (accessToken == null) {
throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling updateProject");
}
HttpHeaders headers = new HttpHeaders();
headers.set("Xero-Tenant-Id", xeroTenantId);
headers.setAccept("application/json");
headers.setUserAgent(this.getUserAgent());
// create a map of path variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("projectId", projectId);
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}");
String url = uriBuilder.buildFromMap(uriVariables).toString();
GenericUrl genericUrl = new GenericUrl(url);
if (logger.isDebugEnabled()) {
logger.debug("PUT " + genericUrl.toString());
}
HttpContent content = null;
content = apiClient.new JacksonJsonHttpContent(projectCreateOrUpdate);
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
HttpTransport transport = apiClient.getHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
return requestFactory.buildRequest(HttpMethods.PUT, genericUrl, content).setHeaders(headers)
.setConnectTimeout(apiClient.getConnectionTimeout())
.setReadTimeout(apiClient.getReadTimeout()).execute();
}
<T> T makePostRequest(
String url, Optional<Map<String, String>> parameters, HttpContent httpContent, Class<T> clazz)
throws IOException, InvalidTokenException, PermissionDeniedException {
// Wait for write permit before making request
writeRateLimiter.acquire();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
HttpRequest postRequest =
requestFactory.buildPostRequest(
new GenericUrl(url + "?" + generateParamsString(parameters)), httpContent);
postRequest.setReadTimeout(2 * 60000); // 2 minutes read timeout
HttpResponse response;
try {
response = postRequest.execute();
} catch (HttpResponseException e) {
response =
handleHttpResponseException(
() ->
requestFactory.buildPostRequest(
new GenericUrl(url + "?" + generateParamsString(parameters)), httpContent),
e);
}
Preconditions.checkState(response.getStatusCode() == 200);
String result =
CharStreams.toString(new InputStreamReader(response.getContent(), Charsets.UTF_8));
if (clazz.isAssignableFrom(String.class)) {
return (T) result;
} else {
return objectMapper.readValue(result, clazz);
}
}
@Override
public <T> T get(String path, Type responseType)
throws RepoException, ValidationException {
HttpRequestFactory requestFactory = getHttpRequestFactory(
getCredentialsIfPresent(uri.toString()));
GenericUrl url = getUrl(path);
try {
return execute(responseType, requestFactory.buildGetRequest(url));
} catch (IOException e) {
throw new RepoException("Error running Gerrit API operation " + url, e);
}
}
@Test
public void testInterceptor() throws URISyntaxException, IOException, RequestSigningException {
wireMockServer.stubFor(get(urlPathEqualTo("/billing-usage/v1/reportSources"))
.withHeader("Authorization", matching(".*"))
.withHeader("Host", equalTo(SERVICE_MOCK))
.willReturn(aResponse()
.withStatus(302)
.withHeader("Location", "/billing-usage/v1/reportSources/alternative")));
wireMockServer.stubFor(get(urlPathEqualTo("/billing-usage/v1/reportSources/alternative"))
.withHeader("Authorization", matching(".*"))
.withHeader("Host", equalTo(SERVICE_MOCK))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody("<response>Some content</response>")));
HttpRequestFactory requestFactory = createSigningRequestFactory();
URI uri = URI.create("https://endpoint.net/billing-usage/v1/reportSources");
HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(uri));
// Mimic what the library does to process the interceptor.
request.setFollowRedirects(true).execute();
List<LoggedRequest> loggedRequests = wireMockServer.findRequestsMatching(RequestPattern
.everything()).getRequests();
MatcherAssert.assertThat(loggedRequests.get(0).getHeader("Authorization"),
Matchers.not(CoreMatchers.equalTo(loggedRequests.get(1).getHeader("Authorization"))));
}
@VisibleForTesting
FirebaseProjectManagementServiceImpl(
FirebaseApp app, Sleeper sleeper, Scheduler scheduler, HttpRequestFactory requestFactory) {
this.app = checkNotNull(app);
this.sleeper = checkNotNull(sleeper);
this.scheduler = checkNotNull(scheduler);
this.requestFactory = checkNotNull(requestFactory);
this.httpHelper = new HttpHelper(app.getOptions().getJsonFactory(), requestFactory);
}
/**
* Specifying a credential, but not a transport, the factory will use the
* transport from the credential.
*/
@Test
public void makeClient_WithCredential() {
NetHttpTransport transport = new NetHttpTransport();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(transport)
.build();
DatastoreOptions options = new DatastoreOptions.Builder()
.projectId(PROJECT_ID)
.credential(credential)
.build();
HttpRequestFactory f = factory.makeClient(options);
assertEquals(transport, f.getTransport());
}
IAMCryptoSigner(
@NonNull HttpRequestFactory requestFactory,
@NonNull JsonFactory jsonFactory,
@NonNull String serviceAccount) {
this.requestFactory = checkNotNull(requestFactory);
this.jsonFactory = checkNotNull(jsonFactory);
checkArgument(!Strings.isNullOrEmpty(serviceAccount));
this.serviceAccount = serviceAccount;
}
public HttpResponse deleteConnectionForHttpResponse(String accessToken, UUID id) throws IOException {
// verify the required parameter 'id' is set
if (id == null) {
throw new IllegalArgumentException("Missing the required parameter 'id' when calling deleteConnection");
}
if (accessToken == null) {
throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling deleteConnection");
}
HttpHeaders headers = new HttpHeaders();
headers.setAccept("");
headers.setUserAgent(this.getUserAgent());
// create a map of path variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("id", id);
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/connections/{id}");
String url = uriBuilder.buildFromMap(uriVariables).toString();
GenericUrl genericUrl = new GenericUrl(url);
if (logger.isDebugEnabled()) {
logger.debug("DELETE " + genericUrl.toString());
}
HttpContent content = null;
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
HttpTransport transport = apiClient.getHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
return requestFactory.buildRequest(HttpMethods.DELETE, genericUrl, content).setHeaders(headers)
.setConnectTimeout(apiClient.getConnectionTimeout())
.setReadTimeout(apiClient.getReadTimeout()).execute();
}
public HttpResponse getAssetSettingsForHttpResponse(String accessToken, String xeroTenantId) throws IOException {
// verify the required parameter 'xeroTenantId' is set
if (xeroTenantId == null) {
throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getAssetSettings");
}
if (accessToken == null) {
throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getAssetSettings");
}
HttpHeaders headers = new HttpHeaders();
headers.set("Xero-Tenant-Id", xeroTenantId);
headers.setAccept("application/json");
headers.setUserAgent(this.getUserAgent());
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Settings");
String url = uriBuilder.build().toString();
GenericUrl genericUrl = new GenericUrl(url);
if (logger.isDebugEnabled()) {
logger.debug("GET " + genericUrl.toString());
}
HttpContent content = null;
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
HttpTransport transport = apiClient.getHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
return requestFactory.buildRequest(HttpMethods.GET, genericUrl, content).setHeaders(headers)
.setConnectTimeout(apiClient.getConnectionTimeout())
.setReadTimeout(apiClient.getReadTimeout()).execute();
}
public HttpResponse createTimeEntryForHttpResponse(String accessToken, String xeroTenantId, UUID projectId, TimeEntryCreateOrUpdate timeEntryCreateOrUpdate) throws IOException {
// verify the required parameter 'xeroTenantId' is set
if (xeroTenantId == null) {
throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createTimeEntry");
}// verify the required parameter 'projectId' is set
if (projectId == null) {
throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling createTimeEntry");
}// verify the required parameter 'timeEntryCreateOrUpdate' is set
if (timeEntryCreateOrUpdate == null) {
throw new IllegalArgumentException("Missing the required parameter 'timeEntryCreateOrUpdate' when calling createTimeEntry");
}
if (accessToken == null) {
throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createTimeEntry");
}
HttpHeaders headers = new HttpHeaders();
headers.set("Xero-Tenant-Id", xeroTenantId);
headers.setAccept("application/json");
headers.setUserAgent(this.getUserAgent());
// create a map of path variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("projectId", projectId);
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}/time");
String url = uriBuilder.buildFromMap(uriVariables).toString();
GenericUrl genericUrl = new GenericUrl(url);
if (logger.isDebugEnabled()) {
logger.debug("POST " + genericUrl.toString());
}
HttpContent content = null;
content = apiClient.new JacksonJsonHttpContent(timeEntryCreateOrUpdate);
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
HttpTransport transport = apiClient.getHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
return requestFactory.buildRequest(HttpMethods.POST, genericUrl, content).setHeaders(headers)
.setConnectTimeout(apiClient.getConnectionTimeout())
.setReadTimeout(apiClient.getReadTimeout()).execute();
}
private HttpRequest subtestConstructor(Credential credential) throws Exception {
MockHttpTransport transport = new MockHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
HttpRequest request = requestFactory.buildDeleteRequest(HttpTesting.SIMPLE_GENERIC_URL);
request.execute();
return request;
}
/**
* firebasePost.
*
* @param path .
* @param object .
* @return .
* @throws IOException .
*/
public HttpResponse firebasePost(String path, Object object) throws IOException {
// Make requests auth'ed using Application Default Credentials
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault().createScoped(FIREBASE_SCOPES);
HttpRequestFactory requestFactory =
httpTransport.createRequestFactory(new HttpCredentialsAdapter(credential));
String json = new Gson().toJson(object);
GenericUrl url = new GenericUrl(path);
return requestFactory
.buildPostRequest(url, new ByteArrayContent("application/json", json.getBytes()))
.execute();
}