SpringBoot:为代理GET Request创建一个请求工厂

时间:2018-09-18 15:48:45

标签: java spring-boot

我正在尝试向另一个API发出GET请求。我还需要通过代理。我尝试实现REST模板请求工厂,但出现连接超时。这是我的控制器:

@RestController
public class AuthenticateController {

    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

        Proxy proxy= new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxyhost", proxyport));
        requestFactory.setProxy(proxy);
        requestFactory.setReadTimeout(3000);
        requestFactory.setConnectTimeout(3000);
        return new RestTemplate(requestFactory);
    }

    @Autowired
    RestTemplate restTemplate;

    @Value("${resources.authenticate}")
    private String authServiceUrl;

    @GetMapping("/authenticate")
    public AuthenticateRto authenticateUser(@RequestParam("api_key") String apiKey) {

        UriComponentsBuilder authenticateUrlBuilder = UriComponentsBuilder.fromUriString(authServiceUrl)
                .queryParam("api_key", apiKey);
        return restTemplate.getForObject(authenticateUrlBuilder.toUriString(), AuthenticateRto.class);
    }
}

我不确定拨打电话时是否设置了代理服务器。

1 个答案:

答案 0 :(得分:1)

更好的方法是使用constructor injection

在配置类中声明RestTemplate bean:

@Configuration
public class ApplicationConfiguration {

  @Bean
  public RestTemplate restTemplate() {
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    Proxy proxy= new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxyhost", proxyport));
    requestFactory.setProxy(proxy);
    requestFactory.setReadTimeout(3000);
    requestFactory.setConnectTimeout(3000);
    return new RestTemplate(requestFactory);
  }

}

然后使用构造函数注入来获取所需的RestTemplate bean:

@RestController
public class AuthenticateController {

  private final RestTemplate restTemplate;

  public AuthenticateController(RestTemplate RestTemplate) {
    this.restTemplate = restTemplate;
  }

  // rest of the controller's logic
}

请注意,由于@Autowired具有一个构造函数,因此可以省略AuthenticateController