如何为Jersey2客户端添加http代理

feu*_*eux 17 jersey-client jersey-2.0

在Jersey1.x上为客户端设置代理很容易:

config.getProperties().put(ApacheHttpClientConfig.PROPERTY_PROXY_URI, proxyUrl);
Run Code Online (Sandbox Code Playgroud)

但是如何为Jersey2.x客户端添加http代理?我检查了源代码并没有找到实现在那里:

org.glassfish.jersey.client.HttpUrlConnector

谢谢!

NGl*_*oom 18

谢谢@feuyeux,解决方案对我有用,ps,下面的代码在代理中使用http basic auth:

    ClientConfig config = new ClientConfig();
    config.connectorProvider(new ApacheConnectorProvider());
    config.property(ClientProperties.PROXY_URI, proxy);
    config.property(ClientProperties.PROXY_USERNAME,user);
    config.property(ClientProperties.PROXY_PASSWORD,pass);
    Client client = JerseyClientBuilder.newClient(config);
Run Code Online (Sandbox Code Playgroud)

希望能帮助别人


feu*_*eux 11

在运行时设置不同的代理不是好的解决方案.因此,我使用apache连接器这样做:

添加定义的apache连接器依赖项:

<dependency>
 <groupId>org.glassfish.jersey.connectors</groupId>
 <artifactId>jersey-apache-connector</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

将apache连接器添加到客户端

config.property(ApacheClientProperties.PROXY_URI, proxyUrl); 
Connector connector = new ApacheConnector(config); 
config.connector(connector); 
Run Code Online (Sandbox Code Playgroud)

  • 这不适用于apache连接器2.17 (6认同)

Lif*_*ube 8

如果你使用jersey 2.0默认的http连接器(这是JDK Http(s)URLConnection).你可以简单地配置代理,如:

    System.setProperty ("http.proxyHost", "proxy_server");
    System.setProperty ("http.proxyPort", "proxy_port");
Run Code Online (Sandbox Code Playgroud)

对于http连接器的其他实现(Apache HTTP Client和Grizzly Asynchronous Client),我之前没有尝试过.但我认为您可以按照http连接器本身的说明进行操作.

  • "在运行时设置不同的代理并不是一个好的解决方案" - 为什么不呢?如果我需要通过不同的网络建立多个连接怎么办?在这种情况下,在运行时设置是必不可少的*. (3认同)

kes*_*hin 5

不包含的替代方案jersey-apache-connector

public class Sample {

  public static void main(String[] args) {

    // you can skip AUTH filter if not required
    ClientConfig config = new ClientConfig(new SampleProxyAuthFilter());
    config.connectorProvider(
        new HttpUrlConnectorProvider().connectionFactory(new SampleConnectionFactory()));

    Client client = ClientBuilder.newClient(config);

    // there you go
  }
}

class SampleConnectionFactory implements HttpUrlConnectorProvider.ConnectionFactory {
  @Override
  public HttpURLConnection getConnection(URL url) throws IOException {
    return (HttpURLConnection) url
        .openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("host", 8080)));
  }
}

class SampleProxyAuthFilter implements ClientRequestFilter {

  @Override
  public void filter(ClientRequestContext requestContext) throws IOException {
    requestContext.getHeaders().add("Proxy-Authorization", "authentication");
  }
}
Run Code Online (Sandbox Code Playgroud)