java.net.UnknownHostException 冷不防 2022-02-01 14:04 179阅读 0赞 32/100 发布文章 ## 问题 ## 快递鸟查询物流的时候,在Window平台下没有问题,在Linux下会出现以下的问题: java.net.UnknownHostException: api.kdniao.com at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at java.net.Socket.connect(Socket.java:538) at sun.net.NetworkClient.doConnect(NetworkClient.java:180) at sun.net.www.http.HttpClient.openServer(HttpClient.java:432) at sun.net.www.http.HttpClient.openServer(HttpClient.java:527) at sun.net.www.http.HttpClient.<init>(HttpClient.java:211) at sun.net.www.http.HttpClient.New(HttpClient.java:308) at sun.net.www.http.HttpClient.New(HttpClient.java:326) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1167) at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1103) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:997) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:931) at com.genersoft.ypzt.yjys.controller.YjysController.sendPost(YjysController.java:444) at com.genersoft.ypzt.yjys.controller.YjysController.getOrderTracesByJson(YjysController.java:334) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ## 方案 ## 修改hosts文件 vi /etc/hosts 134.175.75.136 [api.kdniao.com][] ## 原因 ## 在大多数Linux操作系统中,都是以/etc/hosts中的配置查找主机名的,但是 Detian based system用/etc/Hostname文件中的配置做主机名。 而Java 的InetAddress.java 调用 InetAddressImpl.java 的 public native String getLocalHostName() throws UnknownHostException; 来获取本地主机名, Java 的这个方法是native的,是本地系统的一个实现,所以在本地配置出现问题的情况下,Java 代码出现问题。 分析下代码: /** * Creates a socket and connects it to the specified address on * the specified port. * @param address the address * @param timeout the timeout value in milliseconds, or zero for no timeout. * @throws IOException if connection fails * @throws IllegalArgumentException if address is null or is a * SocketAddress subclass not supported by this socket * @since 1.4 */ protected void connect(SocketAddress address, int timeout) throws IOException { boolean connected = false; try { if (address == null || !(address instanceof InetSocketAddress)) throw new IllegalArgumentException("unsupported address type"); InetSocketAddress addr = (InetSocketAddress) address; if (addr.isUnresolved()) throw new UnknownHostException(addr.getHostName()); //这里出的错误,应该是需要读取host文件 this.port = addr.getPort(); this.address = addr.getAddress(); connectToAddress(this.address, port, timeout); connected = true; } finally { if (!connected) { try { close(); } catch (IOException ioe) { /* Do nothing. If connect threw an exception then it will be passed up the call stack */ } } } } [api.kdniao.com]: http://api.kdniao.com
还没有评论,来说两句吧...