简体   繁体   English

如何使用Java中的InetAddress对象创建URL对象?

[英]how to create a URL object using an InetAddress object in Java?

I have a need to create a http or https URL object from an IPv4 address (String or InetAddress objects - either one is ok) in Java. 我需要从Java中的IPv4地址(字符串或InetAddress对象-可以都可以)创建http或https URL对象。 I have been at this for 10 hours now. 我已经在这里呆了十个小时了。

Attempts that hit a wall described below: 碰壁的尝试如下所述:

  1. Attempt #1: I tried to make the URL by assembling a string, and then feeding it to a URL constructor. 尝试1:我尝试通过组装一个字符串来创建URL,然后将其提供给URL构造函数。

    • Textbook states that a URL can be "protocol://host", with host being either a host name or IP address. 教科书指出URL可以是“ protocol:// host”,其中host可以是主机名或IP地址。 but creating a URL like this: URL a = new URL("http://151.101.65.69"); 但是创建这样的URL: URL a = new URL("http://151.101.65.69"); and opening a stream to this URL ( a ) gives a HTTP error 500 (Internal Server Error - An unexpected condition occurred that the server does not know how to handle). 并打开指向该URL( a )的流将产生HTTP错误500(内部服务器错误-发生了服务器不知道如何处理的意外情况)。
    • What get me fuming is that URL a = new URL("http://stackoverflow.com"); 使我感到困惑的是URL a = new URL("http://stackoverflow.com"); works. 作品。
    • At this point I am stuck. 在这一点上我被困住了。 I have no Idea what to change, or how to move forward. 我不知道该改变什么,或者如何前进。
  2. Attempt #2: I tried to do a reverse lookup on the IP address using "getHostName()" method in the InetAddress class. 尝试2:我尝试使用InetAddress类中的“ getHostName()”方法对IP地址进行反向查找。

    • this should return the host name by doing a reverse DNS lookup. 这应该通过执行反向DNS查找来返回主机名。 Yet, I keep trying it for 151.101.65.69 (stackoverflow web server IP address), and the look up fails. 但是,我一直尝试使用151.101.65.69(stackoverflow Web服务器IP地址),但查找失败。 By fails I mean the IP address is returned as string rather than the host name as a string. 失败是指IP地址以字符串形式返回,而不是以主机名形式返回。 I read the Oracle docs http://docs.oracle.com/javase/1.5.0/docs/api/java/net/InetAddress.html#getHostName() , but I don't understand how to overcome the "security manager" the document mentions (or if it is indeed the reason the reverse lookup fails). 我阅读了Oracle文档http://docs.oracle.com/javase/1.5.0/docs/api/java/net/InetAddress.html#getHostName() ,但我不明白如何克服“安全管理器”文件中提到(或者如果确实是反向查找失败的原因)。
    • I also tried "getCannonicalHostName()", but that didn't fly either. 我也尝试过“ getCannonicalHostName()”,但是那也不行。
  3. I am trying to figure out how to open a website using the IP address. 我试图弄清楚如何使用IP地址打开网站。 It looks like my browser is running into the same issue as my code. 看来我的浏览器遇到了与我的代码相同的问题。 I read up on How to access site through IP address when website is on a shared host? 当网站位于共享主机上时,我读了《 如何通过IP地址访问网站》一书? but I do not have any user names, as I want to be able to open any website that a user has an IP address for. 但是我没有任何用户名,因为我希望能够打开用户拥有IP地址的任何网站。 Adding a port (such as 80) does not seem to work; 添加端口(例如80)似乎无效。 neither does leaving the user name blank or using a generic 'user' or 'guest'. 都不会将用户名留空或使用通用的“用户”或“来宾”。

I need is to create a URL object from an IPv4 String or InetAddress object, and I am stuck. 我需要的是从IPv4 String或InetAddress对象创建URL对象,而我陷入了困境。 I understand that a knowledgeable programmer such as you, may say that making URLs from IP addresses is not what IP addresses are for, or point out that I am not including a file portion of the URL, but that is not the problem at this moment. 我了解像您这样的知识渊博的程序员可能会说从IP地址创建URL并不是IP地址的目的,或者指出我不包括URL的文件部分,但是目前这不是问题。 Could you please help me with my core challenge? 您能帮我解决我的核心挑战吗?

The following code works for me. 以下代码对我有用。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

public class InetAddressMain {

    public static void main(String[] args) {
        try {
            InetAddress addr = InetAddress.getByName("172.217.4.110");

            URL url = new URL("http://"+addr.getHostAddress());
            InputStream is = url.openStream();

            InputStreamReader isReader = new InputStreamReader(is);
            BufferedReader reader = new BufferedReader(isReader);
            String line;
            while((line = reader.readLine()) != null){
                System.out.println(line);
            }

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Output: 输出:

<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for." <!doctype html> <html itemscope =“” itemtype =“ http://schema.org/WebPage” lang =“ zh_CN”> <head> <meta content =“搜索全球信息,包括网页,图像,视频和Google拥有许多特殊功能,可帮助您准确找到所需的内容。” ... [output shortened for readability] ... [缩短输出以提高可读性]

The answer provided by DB is good. DB提供的答案很好。 I had very similar code; 我有非常相似的代码。 but you will find that this code will not work every time. 但是您会发现此代码并非每次都有效。 There are IPv4 addresses you pass to the code offered DB's answer which will not be able to open a URL stream (for example the IP address for stackoverflow). 您有一些IPv4地址传递给提供的DB的答案的代码,这些IPv4地址将无法打开URL流(例如,用于stackoverflow的IP地址)。 I thought the problem was my coding, and that is what I was hoping to get help with on stackoverflow. 我以为问题出在我的编码上,这就是我希望在stackoverflow上获得帮助的原因。 But I now realize the problem was my lack of understanding when asking this question. 但是我现在意识到问题是我在问这个问题时缺乏理解。 What I now understand, is that having an IPv4 address is not sufficient to open every website on the web. 我现在了解的是,拥有IPv4地址不足以打开网络上的每个网站。 Anytime a server hosts multiple websites, the IP address can be used to connect to the server, but not to simultaneously identify the website we want to open/access. 每当服务器托管多个网站时,该IP地址都可用于连接到服务器,但不能同时标识我们要打开/访问的网站。 This gentleman explains this quite well: http://ask-leo.com/why_doesnt_accessing_a_site_by_its_ip_address_work.html 这位先生对此进行了很好的解释: http : //ask-leo.com/why_doesnt_accessing_a_site_by_its_ip_address_work.html

@DB thanks for taking the time to help. @DB感谢您抽出宝贵时间提供帮助。 Much appreciated! 非常感激!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM