【问题标题】:binding network interface to Apache httpclient将网络接口绑定到 Apache httpclient
【发布时间】:2017-01-27 00:12:29
【问题描述】:

我在一台有两个网卡的机器上使用 Apache HttpClient。我找不到如何绑定 HttpClient 以仅使用其中一个 NIC。我找到了一些解决方案,但它们现在都被贬值了。我正在使用 Apache HttpClient 4.5.2

有没有在使用 NIC 绑定时使用 GET/POST 请求的示例?

【问题讨论】:

    标签: apache-httpclient-4.x


    【解决方案1】:

    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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-02-08
      • 1970-01-01
      • 2013-01-06
      • 2016-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多