将字符串转换为Uri

252

我该如何在Java(Android)中将字符串转换为Uri?例如:

String myUrl = "http://stackoverflow.com";

myUri = ???;

我的URI = ???;
8个回答

590

你可以使用Uriparse静态方法。

//...
import android.net.Uri;
//...

Uri myUri = Uri.parse("http://stackoverflow.com")

5
我尝试了这个解决方案,但是遇到了问题。首先,如果Uri来自java.net包,需要将它更改为URI。其次,它没有“parse”构造函数。您有什么想法我做错了什么吗? - Jürgen K.
4
有一个名为Uri的类,它有一个parse方法 http://developer.android.com/reference/android/net/Uri.html 。还有一个没有parse方法的名为URI的类http://developer.android.com/reference/java/net/URI.html。因此,应该使用正确的类`Uri`。确保导入了正确的类。 - ccheneson
2
@ccheneson 为什么 Uri 更加正确,而不是 URI?使用 URI,你只需要使用 create 方法。它和 Uri 的使用一样简单。所以,使用 Uri 有哪些好处呢? - kaba713
没错。错误的导入也是我烦恼的问题之一。 - Omid.N
这就是如此简单 :) - Mateusz Niedbal

54

我只是在使用 java.net 包(package)。在这里,你可以进行以下操作:

...
import java.net.URI;
...

String myUrl = "http://stackoverflow.com";
URI myURI = new URI(myUrl);

12

如果您正在使用Kotlin和 Kotlin Android扩展,则有一种优美的方法来实现此目的。

val uri = myUriString.toUri()

要将Kotlin扩展(KTX)添加到您的项目中,请将以下内容添加到您的应用程序模块的build.gradle中:

  repositories {
    google()
}

dependencies {
    implementation 'androidx.core:core-ktx:1.0.0-rc01'
}

7

您可以使用 Uri.parse() 将字符串解析为 Uri,如下所示:

Uri myUri = Uri.parse("http://stackoverflow.com");

以下是一个示例,展示了如何在隐式意图中使用新创建的Uri,以便在用户手机上使用浏览器查看。
// 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);
}

注意: Android的URIUri之间存在区别。


6
import java.net.URI;

以下内容对我也有效:

URI uri = URI.create("http://stackoverflow.com");

或者

URI uri = new URI("http://stackoverflow.com");

2
Java中的解析器在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());

1
你也可以做到这一点。
对于 http。
var response = await http.get(Uri.http("192.168.100.91", "/api/fetch.php"));

或者
对于https
var response = await http.get(Uri.https("192.168.100.91", "/api/fetch.php"));

0
你打算用URI做什么?
例如,如果你只是想在HttpGet中使用它,那么在创建HttpGet实例时可以直接使用该字符串。
HttpGet get = new HttpGet("http://stackoverflow.com");

3
例如android.widget.ImageView.setImageURI不会 — 所以这是一个完全合理的问题。 - Martin
2
实际上这并没有回答问题。 - Jürgen K.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接