Spring Boot程序使用代理

目录

1.配置文件

1.1读取配置

2.RestTemplate使用代理

3.WebSocket使用代理


1.配置文件

代理配置
applicaiton.properties

proxy.host=127.0.0.1
proxy.port=10809

1.1读取配置

public class ApplicationConfig {
    /// 是否使用代理.
    @Getter
    private static boolean useProxy;
    @Getter
    private static String host;
    @Getter
    private static int port;
    @Getter
    private static String user;
    @Getter
    private static String password;

    private static Properties properties = new Properties();
    public static void load() throws Exception {
        InputStream in = ApplicationContext.class.getClassLoader().getResourceAsStream("application.properties");
        properties.load(in);
        useProxy = properties.containsKey("proxy.host");
        if (useProxy) {
            host = properties.getProperty("proxy.host");
            port = Integer.parseInt(properties.getProperty("proxy.port"));
            user = properties.getProperty("proxy.user");
            password = properties.getProperty("proxy.password");
        }
    }

    static {
        try {
            load();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(String.format("配置错误:%s",e.getMessage()));
        }
    }
}


 

2.RestTemplate使用代理

        String restEndpointUrl = "https://www.okex.com";
        RestTemplate restTemplate;
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.registerModule(new BaseModule());
        objectMapper.registerModule(new OkexApiModule());
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        
        restTemplate = new RestTemplateBuilder()
                        .rootUri(restEndpointUrl)
                        .messageConverters(new MappingJackson2HttpMessageConverter(objectMapper))
                        .additionalInterceptors(new OkexCredentialsRequestInterceptor(false))
                        .errorHandler(new OkexResponseErrorHandler(objectMapper))
                        .build();

        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ApplicationConfig.getHost(), ApplicationConfig.getPort())));

        restTemplate.setRequestFactory(clientHttpRequestFactory);

17-20:设置HTTP代理

 

3.WebSocket使用代理

需要增加依赖:

        <dependency>
            <groupId>org.eclipse.jetty.aggregate</groupId>
            <artifactId>jetty-all</artifactId>
            <version>9.4.9.v20180320</version>
            <type>pom</type>
        </dependency>

示例代码:

        org.springframework.web.socket.client.WebSocketClient webSocketClient;
        if (!ApplicationConfig.isUseProxy()) {
            webSocketClient = new StandardWebSocketClient();
        }
        else {
            HttpClient httpClient = new HttpClient(new SslContextFactory.Client());
            ProxyConfiguration proxyConfig = httpClient.getProxyConfiguration();
            List<ProxyConfiguration.Proxy> proxies = proxyConfig.getProxies();
            HttpProxy proxy = new HttpProxy(ApplicationConfig.getHost(), ApplicationConfig.getPort());
            proxies.add(proxy);
            if (!StringUtils.isEmpty(ApplicationConfig.getUser())) {
                String fullProxy = "http://" + ApplicationConfig.getUser() + ":" + ApplicationConfig.getPassword() + "@" + ApplicationConfig.getHost() + ":" + ApplicationConfig.getPassword();
                AuthenticationStore authenticationStore = httpClient.getAuthenticationStore();
                URI uri = URI.create(fullProxy);
                authenticationStore.addAuthentication(new BasicAuthentication(uri, Authentication.ANY_REALM, ApplicationConfig.getUser(), ApplicationConfig.getPassword()));
            }
            WebSocketClient client = new WebSocketClient(httpClient);
            client.start();
            webSocketClient= new JettyWebSocketClient(client);
        }
        this.webSocketSession = webSocketClient.doHandshake(
                this,
                new WebSocketHttpHeaders(),
                new URI(this.webSocketEnvironment.getWebSocketEndpointUrl())
        ).get();    
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值