gpt4 book ai didi

java - 使用 Spring RestTemplate 通过特定网络接口(interface)发送 HTTP 请求

转载 作者:行者123 更新时间:2023-11-30 01:57:08 24 4
gpt4 key购买 nike

我正在使用 Spring RestTemplate,我需要强制我的客户端通过特定网络接口(interface)发送 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());

binding network interface to Apache httpclient

关于java - 使用 Spring RestTemplate 通过特定网络接口(interface)发送 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54020881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com