我想使用解析的 IP 地址而不是主机名连接到服务器。这是我的代码片段:
// Get domain name from URL
String domainName = url.substring("http://".length(),
url.indexOf("/", 8));
// Get IP address as string
InetAddress inet = null;
try {
inet = InetAddress.getByName(domainName);
} catch (UnknownHostException e) {
Log.i(TAG, "The IP address cannot be resolved for " + domainName);
}
resolvedIP = inet.getHostAddress();
在这里,我能够成功获得 IP 地址。现在我尝试替换我的网址,如下所示:
url = url.replace(domainName, resolvedIP);
Now I connect to server:
URL download = new URL(url);
conn = (HttpURLConnection) url.openConnection();
conn.getInputStream(); //Throws IO Exception
如果我按原样使用 URL(而不用 IP 地址替换域名),我能够成功连接。
如果我做的事情正确,请告诉我。