Twilio Rest Client和设置代理

时间:2015-10-29 00:45:30

标签: java proxy twilio

我正在使用Twilio Java 3.4.5并且我以这种方式设置代理,因为我对Twilio的所有出站请求都必须通过我的代理服务器。

TwilioRestClient client = new TwilioRestClient(twilioSid, twilioAuthToken);
client.setHttpclient(getProxyClient());

private HttpClient getProxyClient() {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(twilioSid, twilioAuthToken)
        );
        CloseableHttpClient httpClient = HttpClients.custom()
                .setRoutePlanner(routePlanner)
                .setDefaultCredentialsProvider(credentialsProvider)
                .build();
        return httpClient;    
    }

我意识到3.4.5超过1.5岁,我尝试升级其中一个最新版本(比如5.0或更高版本)。

我在最新版本的Twilio库中看不到方法.setHttpClient()

当我使用5.0或更高版本时,如何设置代理?

我没有看到任何文件......

2 个答案:

答案 0 :(得分:1)

请忽略这一点,因为在3.4.5中该方法称为setHttpclient()(c为小写),而对于最新的库版本,它是setHttpClient()

答案 1 :(得分:0)

如果您使用的是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();
                Twilio.setRestClient(client);

希望这对你的家伙有帮助