[英]How to produce ConnectException on purpose?
I am using java HttpURLConnection
class to connect to a url, and I want to produce ConnectException to monitor and record some data. 我正在使用java
HttpURLConnection
类连接到url,并且我想产生ConnectException来监视和记录一些数据。 i am just trying to connect random websites but I couldn't be able to produce ConnectionException
even though when I am trying to visit the url which doesn't exist but it is catching MalformedURLException
我只是尝试连接随机网站,但是即使尝试访问不存在但正在捕获
MalformedURLException
的url时,我也无法产生ConnectionException
from Java Docs of ConnectException
, 来自
ConnectException
Java文档,
http://docs.oracle.com/javase/7/docs/api/java/net/ConnectException.html#ConnectException() http://docs.oracle.com/javase/7/docs/api/java/net/ConnectException.html#ConnectException()
Signals that an error occurred while attempting to connect a socket to a remote address and port.
表示尝试将套接字连接到远程地址和端口时发生错误。 Typically, the connection was refused remotely (eg, no process is listening on the remote address/port).
通常,远程拒绝连接(例如,没有进程在远程地址/端口上侦听)。
It means that the connection needed to be refused from the remote server, but I don't know what does that mean and how to produce it from my java code ? 这意味着需要从远程服务器拒绝该连接,但是我不知道这是什么意思,以及如何从我的Java代码生成它?
When you try to connect to an URL that does not exist, two kinds of error can occur: 当您尝试连接到不存在的URL时,会发生两种错误:
In both cases, no ConnectException
will be thrown, because this exception requires that 在这两种情况下,都不会引发
ConnectException
,因为此异常要求
The ConnectException
and the socket basically reside on layers 3 or 4 of the ISO/OSI stack (ie, TCP/IP), whereas your malformed URL is an application layer problem. ConnectException
和套接字基本上位于ISO / OSI堆栈的第3层或第4层(即TCP / IP)上,而格式错误的URL是应用程序层问题。
Your solution: Find a server that has a valid DNS entry, but no listening webserver. 您的解决方案:查找具有有效DNS条目但没有侦听Web服务器的服务器。
::1
should be a safe bet, unless you host a webserver on port 80 yourself. ::1
应该是一个安全的选择,除非您自己在端口80上托管Web服务器。 Here's a minimal working example: 这是一个最小的工作示例:
package Foo;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class TestClass {
public static void main(String[] args) throws IOException {
URL url = new URL("http://localhost");
HttpURLConnection c = (HttpURLConnection)url.openConnection();
c.connect();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.