Convert String to Uri

前端 未结 6 1570
余生分开走
余生分开走 2020-11-30 19:58

How can I convert a String to a Uri in Java (Android)? i.e.:

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

myUri = ???;

相关标签:
6条回答
  • 2020-11-30 20:35

    Java's parser in java.net.URI is going to fail if the URI isn't fully encoded to its standards. For example, try to parse: http://www.google.com/search?q=cat|dog. An exception will be thrown for the vertical bar.

    urllib makes it easy to convert a string to a java.net.URI. It will pre-process and escape the URL.

    assertEquals("http://www.google.com/search?q=cat%7Cdog",
        Urls.createURI("http://www.google.com/search?q=cat|dog").toString());
    
    0 讨论(0)
  • 2020-11-30 20:37

    You can use the parse static method from Uri

    Uri myUri = Uri.parse("http://stackoverflow.com")
    
    0 讨论(0)
  • 2020-11-30 20:37

    What are you going to do with the URI?

    If you're just going to use it with an HttpGet for example, you can just use the string directly when creating the HttpGet instance.

    HttpGet get = new HttpGet("http://stackoverflow.com");
    
    0 讨论(0)
  • 2020-11-30 20:44

    I am just using the java.net package. Here you can do the following:

    String myUrl = "http://stackoverflow.com";
    URI myURI = new URI(myUrl);
    
    0 讨论(0)
  • 2020-11-30 20:45

    If you are using Kotlin and Kotlin android extensions, then there is a beautiful way of doing this.

    val uri = myUriString.toUri()
    

    To add Kotlin extensions (KTX) to your project add the following to your app module's build.gradle

      repositories {
        google()
    }
    
    dependencies {
        implementation 'androidx.core:core-ktx:1.0.0-rc01'
    }
    
    0 讨论(0)
  • 2020-11-30 20:53

    You can parse a String to a Uri by using Uri.parse() as shown below:

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

    The following is an example of how you can use your newly created Uri in an implicit intent. To be viewed in a browser on the users phone.

    // 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);
    }
    

    NB: There is a difference between Androids URI and Uri.

    0 讨论(0)
提交回复
热议问题