如何将字符串转换为Java (Android)的Uri ?例如:
String myUrl = "http://stackoverflow.com";
myUri = ??;
如何将字符串转换为Java (Android)的Uri ?例如:
String myUrl = "http://stackoverflow.com";
myUri = ??;
当前回答
我只是使用java.net包。 在这里你可以做以下事情:
...
import java.net.URI;
...
String myUrl = "http://stackoverflow.com";
URI myURI = new URI(myUrl);
其他回答
可以使用Uri中的解析静态方法
//...
import android.net.Uri;
//...
Uri myUri = Uri.parse("http://stackoverflow.com")
你要对URI做什么?
例如,如果你只是将它与HttpGet一起使用,你可以在创建HttpGet实例时直接使用字符串。
HttpGet get = new HttpGet("http://stackoverflow.com");
import java.net.URI;
以下也适用于我:
URI uri = URI.create("http://stackoverflow.com");
OR
URI uri = new URI("http://stackoverflow.com");
如果你正在使用Kotlin和Kotlin android扩展,那么有一个很好的方法可以做到这一点。
val uri = myUriString.toUri()
要将Kotlin扩展(KTX)添加到项目中,请将以下内容添加到应用模块的build.gradle中
repositories {
google()
}
dependencies {
implementation 'androidx.core:core-ktx:1.0.0-rc01'
}
你也可以这样做
对于http
var response = await http.get(Uri.http("192.168.100.91", "/api/fetch.php"));
or
为https
var response = await http.get(Uri.https("192.168.100.91", "/api/fetch.php"));