How to create a android.net.Uri from a java.net.URL?

后端 未结 6 683
南方客
南方客 2020-12-15 04:21

I would like to use intent.setData(Uri uri) to pass data obtained from a URL. In order to do this, I need to be able to create a Uri from a URL (or from a byte

6条回答
  •  粉色の甜心
    2020-12-15 04:29

    Note that in Android, Uri's are different from Java URI's. Here's how to avoid using hardcoded strings, and at the same time, create a Uri with just the path portion of the http URL string encoded to conform to RFC2396:

    Sample Url String:

    String thisUrl = "http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=[redacted]&mapid=value"
    

    method:

    private Uri.Builder builder;
    public Uri getUriFromUrl(String thisUrl) {
        URL url = new URL(thisUrl);
        builder =  new Uri.Builder()
                                .scheme(url.getProtocol())
                                .authority(url.getAuthority())
                                .appendPath(url.getPath());
        return builder.build();
    }
    

    To handle query strings you will need to parse the url.getQuery() as described here and then feed that into builder. appendQueryParameter().

提交回复
热议问题