我是 FCM 新手,正在编写一个 java 程序来推送消息。我的应用程序服务器位于我们公司场所,通过代理服务器访问互联网。我的问题是如何通过代理获取访问令牌?下面是代码片段
private static String getAccessToken() throws IOException {
GoogleCredential googleCredential = GoogleCredential
.fromStream(new FileInputStream("service-account.json"))
.createScoped(Arrays.asList(SCOPES));
googleCredential.refreshToken();
return googleCredential.getAccessToken();
}
我设法使用匿名 HttpTransportFactory 实现来做到这一点:
var proxyUrl = URI.create(YOUR_PROXY);
var googleCredentials = GoogleCredentials.fromStream(new FileInputStream("service-account.json"),
() -> new NetHttpTransport.Builder()
.setProxy(new Proxy(Type.HTTP, new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())))
.build()
)
.createScoped(Arrays.asList(SCOPES))
.refreshAccessToken();
googleCredentials.refresh();
return googleCredentials.getAccessToken();
请注意,它使用
GoogleCredentials
而不是 GoogleCredential
,因为在撰写此答案时,后者已被弃用。
编辑: 由于您需要为代理提供凭据,因此解决方案变得更加复杂,但这实际上是我最终使用的:
private HttpTransportFactory getHttpTransportFactory(FirebaseProperties properties) {
if (properties.getHttpProxy() == null) {
return ApacheHttpTransport::new;
}
var proxyUrl = URI.create(properties.getHttpProxy());
HttpHost proxyHostDetails = new HttpHost(proxyUrl.getHost(), proxyUrl.getPort());
HttpRoutePlanner httpRoutePlanner = new DefaultProxyRoutePlanner(proxyHostDetails);
HttpClientBuilder httpClientBuilder = ApacheHttpTransport.newDefaultHttpClientBuilder()
.setRoutePlanner(httpRoutePlanner);
if (isNotBlank(properties.getHttpProxyUser())) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(proxyHostDetails.getHostName(), proxyHostDetails.getPort()),
new UsernamePasswordCredentials(properties.getHttpProxyUser(), properties.getHttpProxyPassword()));
httpClientBuilder.setProxyAuthenticationStrategy(ProxyAuthenticationStrategy.INSTANCE)
.setDefaultCredentialsProvider(credentialsProvider);
}
return () -> new ApacheHttpTransport(httpClientBuilder.build());
}
其中
FirebaseProperties
只是自定义 @ConfigurationProperties
类,保存代理连接所需的数据。然后您可以使用 GoogleCredentials.getApplicationDefault(getHttpTransportFactory(properties)).createScoped(MESSAGING_SCOPE)
创建凭证对象