Spring Boot程序使用代理

  • Post author:
  • Post category:其他



目录


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();    



版权声明:本文为wherwh原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。