首页 > 解决方案 > 如果捕获到 IOException,如何关闭 Http URL 连接?- 爪哇

问题描述

我正在尝试制作一个使用不同代理向站点发送发布请求的脚本。这是发送的方法:

public static void send(boolean usingProxyB, int numberOfRequest, String ISP, String phoneNumber, String IP, Integer Port) {

    String url = "";
    String urlParameters = "";

    String ip;
    Integer port;


    if ( (ISP.toLowerCase()).equals("something") || (ISP.toLowerCase()).equals("something") || ISP.equals("something") ) {
        url = "https://www.something.com";
        urlParameters = "paramA=x&paramB=" + phoneNumber + "&paramC=y";
    }

    byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

    try {

        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(IP, Port));
        URL myUrl = new URL(url);

        if (usingProxyB == true) {
            conn = (HttpURLConnection) myUrl.openConnection(proxy);
        } else if (usingProxyB == false) {
            conn = (HttpURLConnection) myUrl.openConnection();
        }




        conn.setDoOutput(true);
        conn.setRequestMethod("POST");

        System.setProperty("sun.net.client.defaultConnectTimeout", "5000");
        System.setProperty("sun.net.client.defaultReadTimeout", "5000");

        conn.setRequestProperty("User-Agent", "Java client");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        conn.getOutputStream().write(postData);

        conn.getInputStream();

        System.out.println("Success on sending SMS #" + numberOfRequest);


    } catch(MalformedURLException e) {

        System.out.println("A - Failed on sending SMS #" + numberOfRequest);

    } catch(ProtocolException e) {

        System.out.println("B - Failed on sending SMS #" + numberOfRequest);

    } catch(IOException e) {

        System.out.println("C - Failed on sending SMS #" + numberOfRequest);

    } finally {
        conn.disconnect();
    }
}

此代码使用不同的代理或使用我自己的 ip 发送 POST 请求。当我使用代理列表时,它会继续打印:“C - 发送 SMS #1 失败”。它不会更改代理,也不会关闭连接。

当代理不起作用或发送请求的时间超过 5 秒时,我想以与打印“发送 SMS #n 成功”时关闭连接相同的方式关闭连接。当我使用自己的 IP,所以我不使用代理列表时,它可以正常工作。请求成功发送,并通过发送另一个请求继续。

我不知道我说的有没有道理,但我的英语说得不太好。

标签: javapostproxytimeout

解决方案


推荐阅读