猿问

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

我想发送此休息电话...


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

...但不能,因为它被编码为


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

这是我的 go 函数:


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)

}

我怎么解决这个问题?提前感谢您的帮助!


更新状态


在您的帮助下,我成功创建了所需的 URL,但我现在面临以下新问题:


&{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>}


这是更新后的代码:


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)

}


FFIVE
浏览 2996回答 1
1回答

慕哥6287543

鉴于服务器不处理百分比编码,请使用基本字符串操作来构造 URI。要解决 net/http 包对 URL 的解码和编码问题,请使用 URL.Opaque 字段指定 URI。func searchOnMavenCentral() {&nbsp; &nbsp; var groupId = "ch.viascom.groundwork"&nbsp; &nbsp; var artifactId = "foxhttp"&nbsp; &nbsp; qp := "q=g:\"" + groupId + `"+AND+a:"` + artifactId + `"` +&nbsp; &nbsp; &nbsp; "&rows=20" +&nbsp; &nbsp; &nbsp; "&core=gav"&nbsp; &nbsp; req, _ := http.NewRequest("GET", "http://search.maven.org", nil)&nbsp; &nbsp; req.URL = &url.URL{&nbsp; &nbsp; &nbsp; &nbsp;Scheme: req.URL.Scheme,&nbsp; &nbsp; &nbsp; &nbsp;Host: req.URL.Host,&nbsp; &nbsp; &nbsp; &nbsp;Opaque: "/solrsearch/select?" + qp,&nbsp; &nbsp; }&nbsp; &nbsp; resp, err := http.DefaultClient.Do(req)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }&nbsp; &nbsp; log.Println(resp.Request.URL)&nbsp; &nbsp; log.Println(resp)}
随时随地看视频慕课网APP

相关分类

Go
我要回答