Extract key, value params from the resources of a

2019-03-03 17:48发布

Hi Everyone I'm working with the next url and I have to get the key-values params from this url the url could be in the next formats:

http://www.espn.com/watch/?gameId=1234&league=nfl&lang=es. In this case I am using the next logic:

def parseUrlStringToMap( def url )
{
    def mapResult
    if ( url.contains( "&" ) || url.contains( "?" ) )
    {
        mapResult = url?.split( '\\?' )[ 1 ]?.split( '&' )?.inject( [:] ) { map, token ->
            token?.split( '=' )?.with { map[ it[ 0 ] ] = it[ 1 ] }
            map
        }
    }
    //Here I have to implement the logic for the second type of url
    def params = new URL( url ).getQuery()
    return mapResult
}

and the second format without parameters is:

http://www.espn.com/fantasy/story/_/id/24664478/fantasy-soccer-la-liga-fantasy-transfer-market-matchweek-4.

I have to extract a map with the [id:24664478]. I have tried using substring. Do you know if is there a sofisticated way to do this without using substring?

Thanks in advance.

2条回答
一夜七次
2楼-- · 2019-03-03 18:25

You could do something like this... I'm assuming that _ denotes that the next 2 elements are a key/value pair... I also changed the code to handle multile values in a query param (ie: k=a&k=b) which is perfectly valid.

def parseUrlStringToMap(URI uri) {
    if (uri.query) {
        uri.query.split('&')*.split("=").inject([:].withDefault { [] }) { m, v ->
            m[v[0]] << v[1]
            m
        }.collectEntries { k, v -> v.size() == 1 ? [k, v[0]] : [k, v] }
    } else {
        // I'm going to assume that key/values come after '_' paths
        def paths = uri.path.split('/')
        paths[paths.findIndexValues { it == '_' }.collect { (it+1)..(it+2) }].collate(2).collectEntries()
    }
}

println parseUrlStringToMap(URI.create('http://www.espn.com/watch/?gameId=1234&league=nfl&lang=es'))
println parseUrlStringToMap(URI.create('http://www.espn.com/fantasy/story/_/id/24664478/_/key/value/fantasy-soccer-la-liga-fantasy-transfer-market-matchweek-4'))
查看更多
何必那么认真
3楼-- · 2019-03-03 18:29
import java.nio.file.Paths

def u=new URL("http://www.espn.com/fantasy/story/id/24664478/fantasy-soccer-la-liga-fantasy-transfer-market-matchweek-4")
def p = Paths.get(u.getPath())

println p[2]
println p[3]

prints

id
24664478
查看更多
登录 后发表回答