将网络接口绑定到 Apache httpclient [英] binding network interface to Apache httpclient
问题描述
我在一台有两个网卡的机器上使用 Apache HttpClient.我找不到如何绑定 HttpClient 以仅使用其中一个 NIC.我找到了一些解决方案,但它们现在都已贬值.我正在使用 Apache HttpClient 4.5.2
I am using Apache HttpClient on a machine which has two network cards. I can not find how I can bind HttpClient to use one of the NICs only. I have found some solutions but they are all depreciated now. I am using Apache HttpClient 4.5.2
是否有使用 NIC 绑定时使用 GET/POST 请求的示例?
Are there any examples that use GET/POST requests while using NIC binding?
推荐答案
Arya ,您必须获得网络接口列表并使用 RequestBuilder 接口来完成此任务.下面会给你一个粗略的想法.
Arya , you will have to get the list of network interfaces and use the RequestBuilder interfaces to get this accomplished. The following will give you a rough cut idea.
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public static void main(String[] args) throws Exception {
//Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
/*if (nifs == null) {
System.err.println("Error getting the Network Interface");
return;
}*/
//A specific network interface can be obtained using getByName
NetworkInterface nif = NetworkInterface.getByName("sup0");
System.out.println("Starting to using the interface: " + nif.getName());
Enumeration<InetAddress> nifAddresses = nif.getInetAddresses();
RequestConfig config = RequestConfig.custom()
.setLocalAddress(nifAddresses.nextElement()).build();
HttpGet httpGet = new HttpGet("http://localhost:8080/admin");
httpGet.setConfig(config);
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
//logic goes here
} finally {
response.close();
}
} finally {
httpClient.close();
}
}
这篇关于将网络接口绑定到 Apache httpclient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!