如何在java中使用代理使twilio工作

时间:2014-03-06 16:45:36

标签: java proxy twilio

我们的应用程序是基于Java的Web应用程序。 在这种情况下,我们无法直接访问第三方api https://api.twilio.com 这必须通过代理完成。 谁能告诉我如何才能为TwilioRestClient实现它?

4 个答案:

答案 0 :(得分:4)

您可以使用.getHttpClient()的{​​{1}}方法并设置代理参数如下:

TwilioRestClient

答案 1 :(得分:3)

我知道这对你来说已经很晚了,但我一直在努力解决这个问题,因为现在不推荐将连接参数直接设置到Apache的HttpClient。这一切都是通过建筑商和工厂完成的。这就是我用Apache httpcomponents 4.3.4:

完成的
HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT, "http");
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
    new UsernamePasswordCredentials(ACCOUNT_SID, ACCOUNT_TOKEN)
    );    
CloseableHttpClient httpClient = HttpClients.custom()
    .setRoutePlanner(routePlanner)
    .setDefaultCredentialsProvider(credentialsProvider)
    .build();
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
client.setHttpclient(httpClient);

//do your regular stuff with this client

希望它有所帮助。

答案 2 :(得分:2)

如果您使用的是7.0.0以上或最新的jar,Twilio提供了自己的HttpClient,请按照以下步骤操作,

1)您需要创建扩展com.twilio.http.HttpClient的customHttpProxy类

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;

import com.google.common.collect.Lists;
import com.twilio.Twilio;
import com.twilio.exception.ApiException;
import com.twilio.http.HttpClient;
import com.twilio.http.HttpMethod;
import com.twilio.http.Request;
import com.twilio.http.Response;

import XXXX.XXX.twilio.util.TwilioUtil;

public class CustomNetworkClient extends HttpClient {

    private static final int CONNECTION_TIMEOUT = 5000;
    private static final int SOCKET_TIMEOUT = 5000;
    private static final int CONNECTIONS_PER_ROUTE = 10;

    private org.apache.http.client.HttpClient client;

    private String twilioRequestId;

    private Float twilioResponseDuration;


    /**
     * Create a new HTTP Client.
     * @throws Exception 
     */
    public CustomNetworkClient() throws Exception {
        this.invokeHttpProxy();
    }

    /**
     * Make a request.
     *
     * @param request request to make
     * @return Response of the HTTP request
     */
    public Response makeRequest(final Request request) {
        twilioResponseDuration = null;
        twilioRequestId = null;

        RequestBuilder builder = RequestBuilder.create(request.getMethod().toString())
            .setUri(request.constructURL().toString())
            .setVersion(HttpVersion.HTTP_1_1)
            .setCharset(StandardCharsets.UTF_8);

        if (request.requiresAuthentication()) {
            builder.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString());
        }

        HttpMethod method = request.getMethod();
        if (method == HttpMethod.POST) {
            builder.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

            for (Map.Entry<String, List<String>> entry : request.getPostParams().entrySet()) {
                for (String value : entry.getValue()) {
                    builder.addParameter(entry.getKey(), value);
                }
            }
        }

        try {
            HttpResponse response = client.execute(builder.build());

            if (response.containsHeader("Twilio-Request-Id"))
                twilioRequestId = response.getFirstHeader("Twilio-Request-Id").getValue();

            if (response.containsHeader("Twilio-Request-Duration"))
                twilioResponseDuration = new Float(response.getFirstHeader("Twilio-Request-Duration").getValue());

            return new Response(
                response.getEntity() == null ? null : response.getEntity().getContent(),
                response.getStatusLine().getStatusCode()
            );            
        } catch (IOException e) {
            throw new ApiException(e.getMessage());
        }
    }

    public String getTwilioRequestId() {
        return twilioRequestId;
    }

    public Float getTwilioResponseDuration() {
        return twilioResponseDuration;
    }


    public  void invokeHttpProxy()throws Exception {
        HttpHost proxy = new HttpHost("YOUR_PROXY_HOST", YOUR_PROXY_PORT, "http");
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);

        //Set up Twilio user credentials
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                    new AuthScope("api.twilio.com", 443), 
                    new UsernamePasswordCredentials(TwilioUtil.ACCOUNT_SID, TwilioUtil.AUTH_TOKEN));

        RequestConfig config = RequestConfig.custom()
            .setConnectTimeout(CONNECTION_TIMEOUT)
            .setSocketTimeout(SOCKET_TIMEOUT)
            .build();

            Collection<Header> headers = Lists.<Header>newArrayList(
                new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION),
                new BasicHeader(HttpHeaders.USER_AGENT, "twilio-java/" + Twilio.VERSION + " (" + Twilio.JAVA_VERSION + ")"),
                new BasicHeader(HttpHeaders.ACCEPT, "application/json"),
                new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8")
            );


        client = HttpClientBuilder.create().setRoutePlanner(routePlanner)
                 .setDefaultCredentialsProvider(credsProvider) 
            .setConnectionManager(new PoolingHttpClientConnectionManager())
            .setDefaultRequestConfig(config)
           .setDefaultHeaders(headers)
            .setMaxConnPerRoute(CONNECTIONS_PER_ROUTE)
            .build();
    }
}

2)分别将自定义类注入Twilio和TwilioRestClient。

 CustomNetworkClient newHttpClient = new CustomNetworkClient();
 Twilio.init(TwilioUtil.ACCOUNT_SID, TwilioUtil.AUTH_TOKEN);
 TwilioRestClient client = new TwilioRestClient.Builder(TwilioUtil.ACCOUNT_SID, TwilioUtil.AUTH_TOKEN).httpClient(newHttpClient)
                .build();`enter code here`
                Twilio.setRestClient(client);

希望这对你的家伙有帮助。

答案 3 :(得分:0)

非常感谢前面提到的。我写了一个比ustomNetworkClient更优雅的类

import com.twilio.http.NetworkHttpClient;
import lombok.RequiredArgsConstructor;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

public class ProxyAuthenticateHttpClient extends NetworkHttpClient {

    private ProxyAuthenticateHttpClient(HttpClientBuilder clientBuilder) {
        super(clientBuilder);
    }

    @RequiredArgsConstructor
    public static class Builder {
        public ProxyAuthenticateHttpClient build() {
            HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            clientBuilder.useSystemProperties();

            RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(CONNECTION_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT)
                .build();

            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                new UsernamePasswordCredentials(proxyUser, proxyPassword));

            PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
            connectionManager.setDefaultMaxPerRoute(10);
            connectionManager.setMaxTotal(10*2);

            clientBuilder
                .setConnectionManager(connectionManager)
                .setDefaultCredentialsProvider(credsProvider)
                .setDefaultRequestConfig(config);

            return new ProxyAuthenticateHttpClient(clientBuilder);
        }

        private final String proxyHost;
        private final int proxyPort;
        private final String proxyUser;
        private final String proxyPassword;

        private static final int CONNECTION_TIMEOUT = 10000;
        private static final int SOCKET_TIMEOUT = 30500;
    }
}

然后使用以下代码初始化Twilio,一切正常

Twilio.init(username, password);
TwilioRestClient.Builder builder = new TwilioRestClient.Builder(username, password);
builder.httpClient(new ProxyAuthenticateHttpClient.Builder(proxyUser, proxyPort, proxyUser, proxyPassword).build());
Twilio.setRestClient(builder.build());