binding network interface to Apache httpclient

2020-04-23 06:56发布

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

Are there any examples that use GET/POST requests while using NIC binding?

1条回答
▲ chillily
2楼-- · 2020-04-23 07:48

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();
    }
}
查看更多
登录 后发表回答