使用 Spring RestTemplate 通过特定网络接口发送 HTTP 请求

Send an HTTP request through a specific network interface using Spring RestTemplate

我正在使用 Spring RestTemplate,我需要强制我的客户端通过特定网络接口发送 HTTP 请求。

我已经找到了使用 java 套接字的解决方案:

NetworkInterface nif = NetworkInterface.getByName("wlan0");
Enumeration<InetAddress> nifAddresses = nif.getInetAddresses();
Socket s = new Socket();
s.bind(new InetSocketAddress(nifAddresses.nextElement(), 0));
s.connect(new InetSocketAddress(host, port));
// Instantiates a new PrintWriter passing in the sockets output stream
PrintWriter wtr = new PrintWriter(s.getOutputStream());
// Prints the request string to the output stream
wtr.println("GET "+path+" HTTP/1.1");
wtr.println("Host: "+host);
wtr.println("");
wtr.flush();
BufferedReader br = new BufferedReader(new 
InputStreamReader(s.getInputStream()));
String content = "";
while ((content=br.readLine()) != null) 
     {
         System.out.println(content);       
     }

有什么方法可以使用 Spring RestTemplate 重现此解决方案?

您需要配置resttemplate使用的http客户端

private ClientHttpRequestFactory getClientHttpRequestFactory() {
NetworkInterface nif = NetworkInterface.getByName("sup0");
Enumeration<InetAddress> nifAddresses = nif.getInetAddresses();
RequestConfig config = RequestConfig.custom()
        .setLocalAddress(nifAddresses.nextElement()).build();

CloseableHttpClient client = HttpClientBuilder
  .create()
  .setDefaultRequestConfig(config)
  .build();
return new HttpComponentsClientHttpRequestFactory(client);

}

然后...

RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());