![](/img/trans.png)
[英]How to split a String result from a JSON URL to individual java objects
[英]how to split string url in java
我想知道如何将字符串 url 拆分为主机和端口。 假设我有
String http://localhost:1213
我想要主机 = "localhost" 和端口(作为整数或长)= 1213。
我这样做了:
String[] parts = URL.split(":");
String HOST = parts[0];
String PORT = parts[1];
但它给了我: HOST = htp// 和 PORT = localhost 显然因为它分裂到“:”如何以正确的方式获取它们并让端口尽可能长而不是字符串有什么帮助?
您可以使用URL类,它还会为您提供验证以确保您的 url 正确。
它有一个getHost
和一个getPort
方法,可以准确地为您提供所需的内容。
URL u = new URL(VAC_URL);
String host = u.getHost();
int port = u.getPort();
如果 URL 无效,构造函数将抛出异常。
如果你想用协议和端口返回你的主机,例如:“ http://127.0.0.1 ”和“9090”所以这是我创建的功能检查......
public static String[] divideHostPort(String hostWithPort) {
String hostProtocol;
String[] urlParts = new String[2];
if (hostWithPort.startsWith("http://")) {
hostProtocol = "http://";
hostWithPort = hostWithPort.replace(hostProtocol, "");
if (hostWithPort.split(":").length == 2) {
urlParts[0] = hostProtocol + hostWithPort.split(":")[0];
urlParts[1] = hostWithPort.split(":")[1];
} else {
urlParts[0] = hostProtocol +hostWithPort;
urlParts[1] = "80";
}
return urlParts;
} else if (hostWithPort.startsWith("https://")) {
hostProtocol = "https://";
hostWithPort = hostWithPort.replace(hostProtocol, "");
if (hostWithPort.split(":").length == 2) {
urlParts[0] = hostProtocol + hostWithPort.split(":")[0];
urlParts[1] = hostWithPort.split(":")[1];
} else {
urlParts[0] = hostProtocol + hostWithPort;
urlParts[1] = "80";
}
return urlParts;
} else {
hostProtocol = "http://";
if (hostWithPort.split(":").length == 2) {
urlParts[0] = hostProtocol + hostWithPort.split(":")[0];
urlParts[1] = hostWithPort.split(":")[1];
} else {
urlParts[0] = hostProtocol + hostWithPort;
urlParts[1] = "80";
}
return urlParts;
}
}
将其String arr[]=divideHostPort("http://127.0.0.1:9090")
要检索这两个详细信息,请使用String host=arr[0]
和String port=arr[1]
数组
String s= http://localhost:1213
String[] parts = s.split(":");
String HOST = parts[1].replaceAll("//",""); // part[0] is http, part[1] is //localhost, part[2] is 1213
String PORT = parts[2];
只需使用Integer.parseInt()
作为端口变量:
String[] parts = VAC_URL.split(":");
String HOST = parts[1].replaceAll("//","");
int PORT = Integer.parseInt(parts[2]);
或者让它长时间使用它:
long PORT = Long.valueOf(parts[2]).longValue();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.