LoginSignup
1
0

More than 5 years have passed since last update.

HerokuからApache HttpClientでOutbound IP固定で通信

Last updated at Posted at 2019-01-31

HerokuアプリからSalesforce APIを発行する際、Salesforce側に許可IPを設定したいのでProximoアドオン(HTTP Proxy)でOutbound IPを固定した
Inboundも固定したいならQuotaGuard Static(のMicro以上)の方がいいかも

ProximoのURLは以下の形式
http://<Proximoユーザ名>:<Proximoパスワード>@proxy-<IPアドレス>.proximo.io
認証が必要なのでそれなりのコーディングを行った

PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
// https://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html 2.4. Multithreaded request execution
// TODO: Tuning
HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(poolingHttpClientConnectionManager);

URL proxyUrl = new URL(<環境変数PROXIMO_URLの値>);
String proxyHostString = proxyUrl.getHost();
int proxyPort = proxyUrl.getPort();
HttpHost proxyHost = proxyPort != -1 ? new HttpHost(proxyUrl.getHost(), proxyPort) : new HttpHost(proxyUrl.getHost());
String proxyUserInfo = proxyUrl.getUserInfo();
String proxyUsername = proxyUserInfo.substring(0, proxyUserInfo.indexOf(':'));
String proxyPassword = proxyUserInfo.substring(proxyUserInfo.indexOf(':') + 1);
httpClientBuilder.setProxy(proxyHost);
httpClientContext = HttpClientContext.create();
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(proxyHost), new UsernamePasswordCredentials(proxyUsername, proxyPassword));
httpClientContext.setCredentialsProvider(credentialsProvider);
BasicScheme basicScheme = new BasicScheme();
basicScheme.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, "Basic"));
BasicAuthCache basicAuthCache = new BasicAuthCache();
basicAuthCache.put(proxyHost, basicScheme);
httpClientContext.setAuthCache(basicAuthCache);

CloseableHttpClient httpClient = httpClientBuilder.build(); // 同じ相手に何度も通信するならcloseすることなく使い回した方が接続やhandshakeにかかる時間を節約できる

HttpGet request = new HttpGet(XXX);
try (CloseableHttpResponse response = httpClient.execute(request, httpClientContext)) {
    String responseBody = EntityUtils.toString(response.getEntity());
    StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
        log.error("XXX failed. statusLine={}, responseBody={}", statusLine.toString(), responseBody);
        throw new RuntimeException("XXX failed");
    }
    ★responseBodyを使って処理
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0