java - 如果捕获到 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¶mB=" + phoneNumber + "¶mC=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,所以我不使用代理列表时,它可以正常工作。请求成功发送,并通过发送另一个请求继续。
我不知道我说的有没有道理,但我的英语说得不太好。
解决方案
推荐阅读
- json - 如何动态地将值添加到 json 对象
- android - 使用 constraintWidth_max 在 TextView 内填充
- perl - 在 perl 中不进行文件比较的递归打印目录路径的优化方法
- typescript - 为什么我可以将空值 `[]` 用于类型化数组接口,而不能将空值 `{}` 用于类型化对象接口?
- c++ - C++ 将派生类列表转换为多态指针列表
- jquery - Ruby on Rails 6. 使用带有 Ajax 的 Bootstrap 4 工具提示
- haskell - # 前缀是什么?
- python-3.x - 执行数据库插入时出现意外的文本连接
- android - 如何获取在启动时立即崩溃的 React Native Android 应用程序的崩溃日志
- javascript - Chrome 扩展:JavaScript 中的字符串比较不起作用