几个 GET 请求在 Java 中时不时地工作不同

问题描述 投票:0回答:0

我写了一个分析本地网络设备的程序。任务的一部分是通过 MAC 地址获取 VENDOR。我写了一个读取所有 MAC 地址的代码,它运行良好。为了通过 MAC 地址获取供应商,我决定使用this API。接下来您将看到该方法,该方法将 MAC 地址作为参数并仅发送 GET 请求:

public static String getVendor(String macAddress) {
        String dataUrl = "https://api.macvendors.com/" + macAddress;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(dataUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                return response.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        return "VENDOR NOT FOUND";
    }

循环调用这段代码:

public static void scanIP(InetAddress ip, NetworkInterface ni) {
        ConcurrentSkipListSet networkIps = scan(ip.toString().substring(1), 254);
        System.out.println("Devices connected to the network:");
        networkIps.forEach(deviceIP -> {
            try {
                System.out.println(deviceIP);
                String MACaddress = getMacAddrHost(InetAddress.getByName((String)deviceIP));
                System.out.println(MACaddress);
                System.out.println(getVendor(MACaddress));
                System.out.println();
            } catch (IOException | InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
    }

问题是这段代码有时完全不同,我的意思是有一次它可以正确返回 Vendor,另一次它返回“NOT FOUND”。

我尝试增加不同的超时时间,设置各种附加参数(这里不需要),但没有帮助。我应该注意到,如果我调试这段代码,它每次都会正确生成供应商。First example Second example

java http https network-programming
© www.soinside.com 2019 - 2024. All rights reserved.