使用HttpURLConnection连接http服务器,如何判断是否连接成功

paodan paodan 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
使用HttpURLConnection连接http服务器,调用connect方法,如果服务器ip和端口正确,无论服务器是否有用户名和密码,URLConnection的connected字段就会返回true,没有判断用户名和密码,是不是HttpURLConnection只发送一个数据包到指定服务器,发现指定的端口打开,connected字段就会返回true?

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public static void testConnect(String surl) throws IOException {
URL url = new URL(surl);
String userInfo = url.getUserInfo();
if (userInfo != null && userInfo.length() > 0) {
String string = surl.replace(userInfo, "");
url = new URL(string);
}
URLConnection connection = (HttpURLConnection) url.openConnection();

if (userInfo != null && userInfo.length() > 0)
connection.setRequestProperty("Authorization", userInfo);
connection.connect();


}
public static void main(String args[]) throws IOException{
String url = "http://192.9.168.11:1122/";//http://user:pass@192.9.168.11:1122/
testConnect(url);
}

请教如何根据HttpURLConnection返回的值判断连接http服务器成功
...全文

相关推荐

评论 41
收藏 已收藏
分享
返回顶部
paodan
Java SE 62,620 成员 307,251 内容