下面列出了怎么用com.google.api.client.http.apache.ApacheHttpTransport的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 构造
*/
void init() {
final HttpRequestConfig httpRequestConfig = getHttpRequestConfig();
if(httpRequestConfig != null && httpRequestConfig.getProxyHost() != null) {
HttpHost proxy = new HttpHost(httpRequestConfig.getProxyHost(), httpRequestConfig.getProxyPort(), httpRequestConfig.getProxyProtocol().toString());
boolean staleConnectionCheck = getHttpConnectionParams().getBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
boolean tcpNodelay = getHttpConnectionParams().getBooleanParameter(HttpConnectionParams.TCP_NODELAY, false);
this.httpTransport = new ApacheHttpTransport.Builder().setProxy(proxy).build();
getHttpConnectionParams().setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, staleConnectionCheck);
getHttpConnectionParams().setBooleanParameter(HttpConnectionParams.TCP_NODELAY, tcpNodelay);
}
this.httpRequestFactory = this.httpTransport.createRequestFactory(
new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) throws IOException {
if (httpRequestConfig != null) {
if (httpRequestConfig.getConnectionTimeout() != -1) {
request.setConnectTimeout(httpRequestConfig.getConnectionTimeout());
}
if (httpRequestConfig.getSocketTimeout() != -1) {
request.setReadTimeout(httpRequestConfig.getSocketTimeout());
}
}
}
});
}
/**
* This methods is used to update a Mendeley documents via the PATCH https://api.mendeley.com/documents/{id} endpoint.
* @param document Pass the document that needs to be updated
*/
public void updateDocument(MendeleyDocument document ){
refreshTokenIfNecessary();
HttpRequestFactory requestFactory = new ApacheHttpTransport().createRequestFactory();
HttpRequest request;
HttpRequest patch_request;
Gson gson = new GsonBuilder().create();
String json_body = gson.toJson(document);
String document_id = document.getId();
String resource_url = "https://api.mendeley.com/documents/" + document_id;
GenericUrl gen_url = new GenericUrl(resource_url);
try {
final HttpContent content = new ByteArrayContent("application/json", json_body.getBytes("UTF8") );
patch_request = requestFactory.buildPatchRequest(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();
}
}
/**
* This methods is used to delete a Mendeley documents via the DELETE https://api.mendeley.com/documents/{id} endpoint.
* @param document Pass the document that needs to be deleted from Mendeley
*/
public void deleteDocument(MendeleyDocument document ){
refreshTokenIfNecessary();
HttpRequestFactory requestFactory = new ApacheHttpTransport().createRequestFactory();
HttpRequest request;
HttpRequest delete_request;
Gson gson = new GsonBuilder().create();
String json_body = gson.toJson(document);
String document_id = document.getId();
String resource_url = "https://api.mendeley.com/documents/" + document_id;
GenericUrl gen_url = new GenericUrl(resource_url);
try {
final HttpContent content = new ByteArrayContent("application/json", json_body.getBytes("UTF8") );
delete_request = requestFactory.buildDeleteRequest(gen_url);
delete_request.getHeaders().setAuthorization("Bearer " + access_token);
delete_request.getHeaders().setContentType("application/vnd.mendeley-document.1+json");
String rawResponse = delete_request.execute().parseAsString();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Create an {@link ApacheHttpTransport} for calling Google APIs with an optional HTTP proxy.
*
* @param proxyUri Optional HTTP proxy URI to use with the transport.
* @param proxyCredentials Optional HTTP proxy credentials to authenticate with the transport
* proxy.
* @return The resulting HttpTransport.
* @throws IOException If there is an issue connecting to Google's certification server.
* @throws GeneralSecurityException If there is a security issue with the keystore.
*/
public static ApacheHttpTransport createApacheHttpTransport(
@Nullable URI proxyUri, @Nullable Credentials proxyCredentials)
throws IOException, GeneralSecurityException {
checkArgument(
proxyUri != null || proxyCredentials == null,
"if proxyUri is null than proxyCredentials should be null too");
ApacheHttpTransport transport =
new ApacheHttpTransport.Builder()
.trustCertificates(GoogleUtils.getCertificateTrustStore())
.setProxy(
proxyUri == null ? null : new HttpHost(proxyUri.getHost(), proxyUri.getPort()))
.build();
if (proxyCredentials != null) {
((DefaultHttpClient) transport.getHttpClient())
.getCredentialsProvider()
.setCredentials(new AuthScope(proxyUri.getHost(), proxyUri.getPort()), proxyCredentials);
}
return transport;
}
@Test
public void signWithHostHeader() throws URISyntaxException, IOException, RequestSigningException {
HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport();
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
URI uri = URI.create("https://ignored-hostname.com/billing-usage/v1/reportSources");
HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(uri));
request.getHeaders().put("Host", "ignored-hostname.com");
GoogleHttpClientEdgeGridRequestSigner googleHttpSigner = new GoogleHttpClientEdgeGridRequestSigner(credential);
googleHttpSigner.sign(request, request);
// NOTE: The library lower-cases all header names.
assertThat(request.getHeaders().containsKey("Host"), is(false));
assertThat(request.getHeaders().containsKey("host"), is(true));
assertThat((String) request.getHeaders().get("host"), equalTo("endpoint.net"));
assertThat(request.getUrl().getHost(), equalTo("endpoint.net"));
assertThat(request.getHeaders().containsKey("authorization"), is(true));
assertThat(request.getHeaders().getAuthorization(), not(isEmptyOrNullString()));
}
/**
* Returns a new instance of {@link ApacheHttpTransport} that uses
* {@link GoogleUtils#getCertificateTrustStore()} for the trusted certificates.
*/
public static ApacheHttpTransport newTrustedTransport() throws GeneralSecurityException,
IOException {
// Set socket buffer sizes to 8192
SocketConfig socketConfig =
SocketConfig.custom()
.setRcvBufSize(8192)
.setSndBufSize(8192)
.build();
PoolingHttpClientConnectionManager connectionManager =
new PoolingHttpClientConnectionManager(-1, TimeUnit.MILLISECONDS);
// Disable the stale connection check (previously configured in the HttpConnectionParams
connectionManager.setValidateAfterInactivity(-1);
// Use the included trust store
KeyStore trustStore = GoogleUtils.getCertificateTrustStore();
SSLContext sslContext = SslUtils.getTlsSslContext();
SslUtils.initSslContext(sslContext, trustStore, SslUtils.getPkixTrustManagerFactory());
LayeredConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);
HttpClient client = HttpClientBuilder.create()
.useSystemProperties()
.setSSLSocketFactory(socketFactory)
.setDefaultSocketConfig(socketConfig)
.setMaxConnTotal(200)
.setMaxConnPerRoute(20)
.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
.setConnectionManager(connectionManager)
.disableRedirectHandling()
.disableAutomaticRetries()
.build();
return new ApacheHttpTransport(client);
}
@Override
public HttpTransport create() {
if (proxyConfig == null) {
return DEFAULT_TRANSPORT;
}
final Proxy proxy = proxyConfig.createProxy();
if (Proxy.Type.HTTP.equals(proxy.type()) && proxyConfig.hasCredential()) {
// If it requires authentication via username and password, use ApacheHttpTransport
final String host = proxyConfig.getProxyServerHost();
final int port = proxyConfig.getProxyServerPort();
final HttpHost proxyHost = new HttpHost(host, port);
final DefaultHttpClient httpClient = new DefaultHttpClient();
ConnRouteParams.setDefaultProxy(httpClient.getParams(), proxyHost);
if (proxyConfig.hasCredential()) {
final AuthScope proxyAuthScope = new AuthScope(host, port);
final UsernamePasswordCredentials proxyCredential
= new UsernamePasswordCredentials(proxyConfig.getProxyUserName(), proxyConfig.getProxyUserPassword());
final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(proxyAuthScope, proxyCredential);
httpClient.setCredentialsProvider(credentialsProvider);
}
return new ApacheHttpTransport(httpClient);
}
return new NetHttpTransport.Builder().setProxy(proxy).build();
}
private HttpRequestFactory createSigningRequestFactory() {
HttpTransport httpTransport = new ApacheHttpTransport.Builder()
.setSocketFactory(SSLSocketFactory.getSystemSocketFactory())
.build();
return httpTransport.createRequestFactory(new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) throws IOException {
request.setInterceptor(new GoogleHttpClientEdgeGridInterceptor(credential));
}
});
}
@Test
public void signEachRequest() throws URISyntaxException, IOException, RequestSigningException {
HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport();
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
URI uri = URI.create("https://ignored-hostname.com/billing-usage/v1/reportSources");
HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(uri));
GoogleHttpClientEdgeGridRequestSigner googleHttpSigner = new GoogleHttpClientEdgeGridRequestSigner(credential);
googleHttpSigner.sign(request, request);
assertThat(request.getHeaders().containsKey("host"), is(false));
assertThat(request.getUrl().getHost(), equalTo("endpoint.net"));
assertThat(request.getHeaders().containsKey("authorization"), is(true));
assertThat(request.getHeaders().getAuthorization(), not(isEmptyOrNullString()));
}
private HttpRequestFactory createSigningRequestFactory() {
HttpTransport httpTransport = null;
try {
httpTransport = new ApacheHttpTransport.Builder().doNotValidateCertificate().build();
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
return httpTransport.createRequestFactory(new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) throws IOException {
request.setInterceptor(new GoogleHttpClientEdgeGridInterceptor(credential));
}
});
}
public HttpParams getHttpConnectionParams() {
return ((ApacheHttpTransport)this.httpTransport).getHttpClient().getParams();
}
public void setStaleCheckingEnabled(boolean enabled){
((ApacheHttpTransport)this.httpTransport).getHttpClient().getParams().setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, enabled);
}
public void setTcpNoDelay(boolean enabled) {
((ApacheHttpTransport)this.httpTransport).getHttpClient().getParams().setBooleanParameter(HttpConnectionParams.TCP_NODELAY, enabled);
}
@Override
public HttpTransport getHttpTransport() {
return new ApacheHttpTransport();
}
public TestApp() {
String projectId = ServiceOptions.getDefaultProjectId();
try {
//export GRPC_PROXY_EXP=localhost:3128
HttpHost proxy = new HttpHost("127.0.0.1",3128);
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
httpClient.addRequestInterceptor(new HttpRequestInterceptor(){
@Override
public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException {
//if (request.getRequestLine().getMethod().equals("CONNECT"))
// request.addHeader(new BasicHeader("Proxy-Authorization","Basic dXNlcjE6dXNlcjE="));
}
});
mHttpTransport = new ApacheHttpTransport(httpClient);
HttpTransportFactory hf = new HttpTransportFactory(){
@Override
public HttpTransport create() {
return mHttpTransport;
}
};
credential = GoogleCredentials.getApplicationDefault(hf);
CredentialsProvider credentialsProvider = new GoogleCredentialsProvider(){
public List<String> getScopesToApply(){
return Arrays.asList("https://www.googleapis.com/auth/pubsub");
}
public Credentials getCredentials() {
return credential;
}
};
TopicAdminSettings topicAdminSettings =
TopicAdminSettings.newBuilder().setCredentialsProvider(credentialsProvider)
.build();
TopicAdminClient topicAdminClient =
TopicAdminClient.create(topicAdminSettings);
//TopicAdminClient topicAdminClient = TopicAdminClient.create();
ProjectName project = ProjectName.create(projectId);
for (Topic element : topicAdminClient.listTopics(project).iterateAll())
System.out.println(element.getName());
} catch (Exception ex)
{
System.out.println("ERROR " + ex);
}
}
public TestApp() {
try
{
/*
JacksonFactory jsonFactory = new JacksonFactory();
Authenticator.setDefault(
new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"user1", "user1".toCharArray());
}
}
);
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 3128));
NetHttpTransport mHttpTransport = new NetHttpTransport.Builder().setProxy(proxy).build();
*/
HttpHost proxy = new HttpHost("127.0.0.1",3128);
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
httpClient.addRequestInterceptor(new HttpRequestInterceptor(){
@Override
public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException {
//if (request.getRequestLine().getMethod().equals("CONNECT"))
// request.addHeader(new BasicHeader("Proxy-Authorization","Basic dXNlcjE6dXNlcjE="));
}
});
mHttpTransport = new ApacheHttpTransport(httpClient);
/*
com.google.api.client.googleapis.auth.oauth2.GoogleCredential credential = com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(mHttpTransport,jsonFactory);
if (credential.createScopedRequired())
credential = credential.createScoped(Arrays.asList(StorageScopes.DEVSTORAGE_READ_ONLY));
com.google.api.services.storage.Storage service = new com.google.api.services.storage.Storage.Builder(mHttpTransport, jsonFactory, credential)
.setApplicationName("oauth client")
.build();
com.google.api.services.storage.model.Buckets dl = service.buckets().list("mineral-minutia-820").execute();
for (com.google.api.services.storage.model.Bucket bucket: dl.getItems())
System.out.println(bucket.getName());
*/
// System.setProperty("https.proxyHost", "localhost");
// System.setProperty("https.proxyPort", "3128");
/*
Authenticator.setDefault(
new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"user1", "user1".toCharArray());
}
}
);
*/
HttpTransportFactory hf = new HttpTransportFactory(){
@Override
public HttpTransport create() {
return mHttpTransport;
}
};
com.google.auth.oauth2.GoogleCredentials credential = com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(hf);
if (credential.createScopedRequired())
credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/devstorage.read_write"));
TransportOptions options = HttpTransportOptions.newBuilder().setHttpTransportFactory(hf).build();
com.google.cloud.storage.Storage storage = com.google.cloud.storage.StorageOptions.newBuilder()
.setCredentials(credential)
.setProjectId("mineral-minutia-820")
.setTransportOptions(options)
.build().getService();
System.out.println("My buckets:");
for (com.google.cloud.storage.Bucket bucket : storage.list().iterateAll())
System.out.println(bucket);
}
catch (Exception ex) {
System.out.println("Error: " + ex);
}
}
/**
* Provide a {@link TransportOptions} backed by Apache HTTP Client.
*
* @see ApacheHttpTransport
* @return customized {@link TransportOptions} to use for our Google client instances
*/
TransportOptions transportOptions() {
return HttpTransportOptions.newBuilder()
.setHttpTransportFactory(() -> new ApacheHttpTransport(newHttpClient()))
.build();
}
/**
* Returns a new thread-safe HTTP transport instance that is compatible with Android SDKs prior to
* Gingerbread.
*
* <p>Don't use this for Android applications that anyway require Gingerbread. Instead just call
* {@code new NetHttpTransport()}.
*
* <p>Prior to Gingerbread, the {@link HttpURLConnection} implementation was buggy, and the Apache
* HTTP Client was preferred. However, starting with Gingerbread, the {@link HttpURLConnection}
* implementation bugs were fixed, and is now better supported than the Apache HTTP Client. There
* is no guarantee that Apache HTTP transport will continue to work in future SDKs. Therefore,
* this method uses {@link NetHttpTransport} for Gingerbread or higher, and otherwise {@link
* ApacheHttpTransport}.
*/
public static HttpTransport newCompatibleTransport() {
return AndroidUtils.isMinimumSdkLevel(9) ? new NetHttpTransport() : new ApacheHttpTransport();
}