Apache HTTP客户端,来自特定网络接口的请求

时间:2013-09-07 11:21:28

标签: java apache apache-httpclient-4.x

我有4台互联网IP的机器,我想知道我是否可以让apache http客户端从特定的ip / network接口发出请求

2 个答案:

答案 0 :(得分:5)

使用HttpClient 4.3 API

    RequestConfig config = RequestConfig.custom()
            .setLocalAddress(InetAddress.getByAddress(new byte[] {127,0,0,1}))
            .build();
    HttpGet httpGet = new HttpGet("/stuff");
    httpGet.setConfig(config);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        CloseableHttpResponse response = httpClient.execute(httpGet);
        try {
            // do something useful
        } finally {
            response.close();
        }
    } finally {
        httpClient.close();
    }

答案 1 :(得分:0)

从未这样做,但API中有一个ClientConnectionOperator接口(以及一些工厂)来创建套接字。也许您可以实现自己的并使用具体的接口创建套接字。