1
我在具有兩個網卡的計算機上使用Apache HttpClient。我找不到如何綁定HttpClient來使用其中一個NIC。我找到了一些解決方案,但現在都已折舊。我正在使用Apache HttpClient 4.5.2綁定到Apache的網絡接口httpclient
是否有任何示例在使用NIC綁定時使用GET/POST請求?
我在具有兩個網卡的計算機上使用Apache HttpClient。我找不到如何綁定HttpClient來使用其中一個NIC。我找到了一些解決方案,但現在都已折舊。我正在使用Apache HttpClient 4.5.2綁定到Apache的網絡接口httpclient
是否有任何示例在使用NIC綁定時使用GET/POST請求?
Arya,您將不得不獲得網絡接口列表並使用RequestBuilder接口來完成此任務。以下將給你一個粗略的想法。
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();
}
}