binding network interface to Apache httpclient

心不动则不痛 提交于 2019-12-02 07:14:53
Ramachandran.A.G

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();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!