douliedu335997
douliedu335997
2019-08-05 21:48

如何在http.Get请求中使用双引号和冒号作为查询字符串?

已采纳

I would like to send this rest call ...

GET http://search.maven.org/solrsearch/select?q=g:"ch.viascom.groundwork"+AND+a:"foxhttp"&rows=100&core=gav

... but can't because it gets encoded to

http://search.maven.org/solrsearch/select?core=gav&q=g%3A%22ch.viascom.groundwork%22%2BAND%2Ba%3A%22foxhttp%22&rows=20

This is my go function:

func searchOnMavenCentral() {
    var groupId = "ch.viascom.groundwork"
    var artifactId = "foxhttp"

    params := url.Values{}
    params.Add("q", `g:"` + groupId + `"+AND+a:"` + artifactId + `"`)
    params.Add("rows", "20")
    params.Add("core", "gav")

    resp, err := http.Get("http://search.maven.org/solrsearch/select?" + params.Encode())
    if err != nil {
        log.Fatalln(err)
    }

    log.Println(resp.Request.URL)
    log.Println(resp)
}

How can I solve this problem? Thx for your help in advance!

Updated state

With your help I managed to create the desired URL, but I'm facing the following new issue now:

&{400 Bad Request 400 HTTP/1.1 1 1 map[Connection:[keep-alive] Date:[Mon, 05 Aug 2019 23:56:45 GMT] Server:[nginx/1.14.1]] 0xc00011a080 -1 [chunked] false false map[] 0xc0000d4000 <nil>}

This is the updated code:

func searchOnMavenCentral() {
    var groupId = "ch.viascom.groundwork"
    var artifactId = "foxhttp"

    qp := "q=g:\"" + groupId + `"+AND+a:"` + artifactId + `"` +
        "&rows=20" +
        "&core=gav"

    u := &url.URL{
        Scheme:   "http",
        Host:     "search.maven.org",
        Path:     "/solrsearch/select",
        RawQuery: qp,
    }

    resp, err := http.Get (u.String())
    if err != nil {
        log.Fatalln(err)
    }

    log.Println(resp.Request.URL)
    log.Println(resp)
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongzhashou0116 dongzhashou0116 2年前

    Given that server does not handle percent encoding, use basic string operations to construct the URI.

    To work around the decoding and encoding of URLs by the net/http package, use the URL.Opaque field to specify the URI.

    func searchOnMavenCentral() {
        var groupId = "ch.viascom.groundwork"
        var artifactId = "foxhttp"
    
        qp := "q=g:\"" + groupId + `"+AND+a:"` + artifactId + `"` +
          "&rows=20" +
          "&core=gav"
    
        req, _ := http.NewRequest("GET", "http://search.maven.org", nil)
        req.URL = &url.URL{
           Scheme: req.URL.Scheme,
           Host: req.URL.Host,
           Opaque: "/solrsearch/select?" + qp,
        }
        resp, err := http.DefaultClient.Do(req)
        if err != nil {
            log.Fatalln(err)
        }
    
        log.Println(resp.Request.URL)
        log.Println(resp)
    }
    
    点赞 评论 复制链接分享

相关推荐