JAVA:如何创建http url连接选择要使用的IP地址 [英] JAVA: How to create http url connection selecting the ip address to use

查看:143
本文介绍了JAVA:如何创建http url连接选择要使用的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在多个NIC上配置了一个公共IP地址池。
在我的JAVA项目中运行LINUX机器,我需要从池中选择一个特定的ip地址,并使用该ip创建一个HttpURLConnecion。此外,我将循环使用池,每次使用不同的ip。

I have a pool of public ip addresses configured on my multiple NICs. In my JAVA project, which runs on a LINUX machine, I need to select a specific ip address from the pool and create an HttpURLConnecion using that ip. Further, I will cycle on the pool, using each time a different ip.

在当前阶段,我无法使用java.net库找到解决方案。我宁愿看一下Apache的HttpClient。在以下链接中, http://hc.apache.org /httpcomponents-client-ga/tutorial/html/connmgmt.html ,据说这样的库可以支持我正在寻找的功能。有关这方面的讨论可以在使用Apache HttpClient定义源IP地址。实际上,发布的帖子似乎没有定论,因为用户的体验与所描述的图书馆使用形成鲜明对比。

At the current stage, I was not able to find a solution using the java.net library. I have rather looked at the HttpClient from Apache. At the following link, http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html, it is said that such library can support the functionality I was looking for. A discussion on this can be found at Define source ip address using Apache HttpClient. Actually, the posted thread seems not conclusive, as users' experiences are very contrasting on the described use of the library.

因此,我认为SO社区并不真实成功地解决了这个问题。事实上,可以在SO上找到关于这个主题的几个重播问题/答案,但是它们似乎都没有对问题进行详尽的分析。

Therefore, I don't think that SO community really succeeded in solving this issue. It is a matter of fact that several replayed questions/answers on this topic can be found on SO, but none of them seems to give an exhaustive analysis of the problem.

而且,问题并没有面对使用java.net库(就像在我的项目中一样)。

Moreover, the problem is not faced with the use of java.net library (as in my project) at all.

目前,我有一个可能的选择是调用一些LINUX系统命令(来自java)来切换NIC以用于当前连接。但是,我还没弄清楚。

At the moment, a possible option that I have is to invoke some LINUX system commands (from java) to switch the NIC to use for the current connection. However, I have not figure it out yet.

因此,如果有任何积极解决此问题的用户能够解决我的问题,我将不胜感激/想法/方法。

Therefore, I would appreciate if any users, who had POSITIVE experiences in solving this issue, can address me to a solution/idea/method.

提前致谢,

Marcello

更新:

我目前已实施此测试代码。它给了我正确的状态代码(200)。但是,它需要使用多个IP地址进行测试。

I've currently implemented this test code. It gives me correct status code (200). However, it needs to be tested with multiple ip addresses.

public class test {

    public static void main(String[] args) {

        final String authUser = "admin";
        final String authPassword = "password";
        Authenticator.setDefault(
           new Authenticator() {
              public PasswordAuthentication getPasswordAuthentication() {
                 return new PasswordAuthentication(
                       authUser, authPassword.toCharArray());
              }
           }
        );

        System.setProperty("http.proxyUser", authUser);
        System.setProperty("http.proxyPassword", authPassword);

        try {

            Properties systemProperties = System.getProperties();
            URL url = new URL("yourURL");
            systemProperties.setProperty("http.proxyHost","localhost");
            systemProperties.setProperty("http.proxyPort", "8080");                         

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            int status = connection.getResponseCode();
            System.out.println(status);

        } catch (IOException e) {
            System.out.println("connection problems");
        }
    }

}

此处您应该能够配置与每个NIC相关的不同TCP端口。有没有人尝试这样的东西?
我期待着阅读新的想法/评论。

At this point, you should be able to configure the different TCP ports related to each NIC. Did anyone try something like this? I am looking forward to reading new ideas/comments.

更新2:
确切地说,我'包括需要它的人的身份验证设置。

UPDATE 2: To be precise, I've included authentication setup for those who needed it.

推荐答案

为什么不使用org.apache.httpcomponents?

Why don't you just use org.apache.httpcomponents?

这里有一个有效的例子(使用maven插件org.apache.httpcomponents,版本4.3.1):

Here an example that works (using maven plugin org.apache.httpcomponents, version 4.3.1):

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class HttpClientExample {

    public void gogo() throws ClientProtocolException, IOException {

        CloseableHttpClient httpclient = HttpClients.createDefault();

        // Local interface1:
        byte ip1[] = new byte[] { (byte)192, (byte)168, (byte)100, (byte)32 };
        // Local interface2:
        byte ip2[] = new byte[] { (byte)192, (byte)168, (byte)100, (byte)33 };


        RequestConfig requestConfig = RequestConfig.custom().setLocalAddress(InetAddress.getByAddress(ip1)).build();
        try {
            HttpGet httpget = new HttpGet("http://server.com");
            httpget.setConfig(requestConfig);
            System.out.println("executing request" + httpget.getRequestLine());
            StringBuilder response = httpclient.execute(httpget,handler);
            System.out.println(response.toString());

            requestConfig = RequestConfig.custom().setLocalAddress(InetAddress.getByAddress(ip2)).build();
            httpget = new HttpGet("http://server.com");
            httpget.setConfig(requestConfig);
            System.out.println("executing request" + httpget.getRequestLine());
            response = httpclient.execute(httpget,handler);
            System.out.println(response.toString());
        } finally {
            httpclient.close();
        }
    }

    private final ResponseHandler<StringBuilder> handler = new ResponseHandler<StringBuilder>() {
        @Override
        public StringBuilder handleResponse(final HttpResponse response)
                throws ClientProtocolException, IOException {
            return sortResponse(response);
        }
    };

    private StringBuilder sortResponse(final HttpResponse httpResponse) throws IOException {
        StringBuilder builder = null;

        if (httpResponse != null) {
            switch (httpResponse.getStatusLine().getStatusCode()) {
                case HttpStatus.SC_OK:
                    final HttpEntity entity = httpResponse.getEntity();
                    if (entity != null) {

                        final InputStreamReader instream = new InputStreamReader(entity.getContent());
                        try {
                            final BufferedReader reader = new BufferedReader(instream);
                            builder = new StringBuilder();
                            String currentLine = null;
                            currentLine = reader.readLine();
                            while (currentLine != null) {
                                builder.append(currentLine).append("\n");
                                currentLine = reader.readLine();
                            }
                        } finally {
                            instream.close();
                        }
                    }
                    break;
                default:
                    throw new IllegalArgumentException("Error.");
            }
        }
        return builder;
    }
}

这篇关于JAVA:如何创建http url连接选择要使用的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆