我该如何在Java(Android)中将字符串转换为Uri?例如:
String myUrl = "http://stackoverflow.com";
myUri = ???;
我的URI = ???;你可以使用Uri
的parse
静态方法。
//...
import android.net.Uri;
//...
Uri myUri = Uri.parse("http://stackoverflow.com")
我只是在使用 java.net
包(package)。在这里,你可以进行以下操作:
...
import java.net.URI;
...
String myUrl = "http://stackoverflow.com";
URI myURI = new URI(myUrl);
如果您正在使用Kotlin和 Kotlin Android扩展,则有一种优美的方法来实现此目的。
val uri = myUriString.toUri()
要将Kotlin扩展(KTX)添加到您的项目中,请将以下内容添加到您的应用程序模块的build.gradle中:
repositories {
google()
}
dependencies {
implementation 'androidx.core:core-ktx:1.0.0-rc01'
}
您可以使用 Uri.parse() 将字符串解析为 Uri,如下所示:
Uri myUri = Uri.parse("http://stackoverflow.com");
// Creates a new Implicit Intent, passing in our Uri as the second paramater.
Intent webIntent = new Intent(Intent.ACTION_VIEW, myUri);
// Checks to see if there is an Activity capable of handling the intent
if (webIntent.resolveActivity(getPackageManager()) != null){
startActivity(webIntent);
}
import java.net.URI;
以下内容对我也有效:
URI uri = URI.create("http://stackoverflow.com");
或者
URI uri = new URI("http://stackoverflow.com");
java.net.URI
中,如果URI没有按照其标准进行完全编码,则会失败。例如,请尝试解析:http://www.google.com/search?q=cat|dog
。竖杠将引发异常。
urllib使将字符串转换为java.net.URI
变得容易。它将预处理并转义URL。assertEquals("http://www.google.com/search?q=cat%7Cdog",
Urls.createURI("http://www.google.com/search?q=cat|dog").toString());
var response = await http.get(Uri.http("192.168.100.91", "/api/fetch.php"));
var response = await http.get(Uri.https("192.168.100.91", "/api/fetch.php"));
HttpGet get = new HttpGet("http://stackoverflow.com");
android.widget.ImageView.setImageURI
不会 — 所以这是一个完全合理的问题。 - Martin
Uri
的类,它有一个parse
方法 http://developer.android.com/reference/android/net/Uri.html 。还有一个没有parse
方法的名为URI
的类http://developer.android.com/reference/java/net/URI.html。因此,应该使用正确的类`Uri`。确保导入了正确的类。 - cchenesoncreate
方法。它和 Uri 的使用一样简单。所以,使用 Uri 有哪些好处呢? - kaba713