代码之家  ›  专栏  ›  技术社区  ›  rasilvap

从url的资源中提取key,value参数

  •  0
  • rasilvap  · 技术社区  · 6 年前

    大家好,我正在处理下一个url,我必须从该url获取键值params该url可以采用以下格式:

    http://www.espn.com/watch/?gameId=1234&league=nfl&lang=es . 在本例中,我使用下一个逻辑:

    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
    }
    

    第二种不带参数的格式是:

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

    我必须提取一张带有[id:24664478]的地图。我试过使用子字符串。你知道有没有一种简单的方法不用子串就可以做到这一点?

    提前谢谢。

    2 回复  |  直到 6 年前
        1
  •  0
  •   tim_yates    6 年前

    你可以这样做。。。我是这么想的 _ 表示接下来的两个元素是键/值对。。。我还更改了代码以处理查询参数中的multile值(即: k=a&k=b )这是完全正确的。

    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'))
    
        2
  •  0
  •   daggett    6 年前
    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]
    

    id
    24664478