带有参数的 Golang HTTP GET 请求

要在 Go 中使用参数发出 HTTP GET 请求,您可以使用 http 包和 net/url 包来构建带有参数的 URL。下面是如何执行此操作的示例:

package main

import (
    "fmt"
    "net/http"
    "net/url"
)

func main() {
    baseURL := "http://example.com"
    resource := "/path"
    params := url.Values{}
    params.Add("param1", "value1")
    params.Add("param2", "value2")

    u, _ := url.ParseRequestURI(baseURL)
    u.Path = resource
    u.RawQuery = params.Encode()
    urlStr := fmt.Sprintf("%v", u) // "http://example.com/path?param1=value1&param2=value2"

    resp, err := http.Get(urlStr)
    // handle error and response
}

此示例通过分析基 URL、设置所需资源的路径以及对查询字符串中的参数进行编码来创建新 URL。然后,它向最终 URL 发出 GET 请求。


示例-2下面是在 Go 中使用查询字符串中的参数发出 HTTP GET 请求的示例:

package main

import (
    "fmt"
    "net/http"
    "net/url"
)

func main() {
    baseURL, _ := url.Parse("http://example.com")
    params := url.Values{}
    params.Add("param1", "value1")
    params.Add("param2", "value2")
    baseURL.RawQuery = params.Encode()

    resp, _ := http.Get(baseURL.String())
    defer resp.Body.Close()
    fmt.Println(resp.Status)
}

这将向“http://example.com?param1=value1¶m2=value2”发出 GET 请求并打印响应的状态。


示例-3要在 Go 中使用参数发出 HTTP GET 请求,您可以使用 net/http 包。下面是一个如何操作的示例:

package main

import (
    "fmt"
    "net/http"
    "net/url"
)

func main() {
    // Define the parameters
    params := url.Values{}
    params.Add("param1", "value1")
    params.Add("param2", "value2")

    // Create the URL with the parameters
    url := "https://example.com?" + params.Encode()

    // Make the GET request
    resp, err := http.Get(url)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()

    // Do something with the response
    // ...
}

在上面的示例中,我们首先使用 url 定义参数。Values 对象。接下来,我们通过使用 Encode() 方法将参数附加到基本 URL 的末尾来创建 URL。最后,我们使用 http 发出 GET 请求。get() 函数并根据需要处理响应。

Was this helpful?

0 / 0

发表回复 0