golang-http请求
- 发送GET请求
import (
"fmt"
"net/http"
)
func main() {
resp, err := http.Get("http://www.example.com/")
if err != nil {
// 处理错误
}
defer resp.Body.Close()
// 处理响应
fmt.Println(resp.StatusCode)
}
- 发送POST请求
import (
"bytes"
"fmt"
"net/http"
)
func main() {
url := "http://www.example.com/post"
jsonStr := []byte(`{"username":"admin","password":"admin"}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
// 处理错误
}
defer resp.Body.Close()
// 处理响应
fmt.Println(resp.StatusCode)
}
- 发送PUT请求
import (
"bytes"
"fmt"
"net/http"
)
func main() {
url := "http://www.example.com/put"
jsonStr := []byte(`{"username":"admin","password":"admin"}`)
req, err := http.NewRequest("PUT", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
// 处理错误
}
defer resp.Body.Close()
// 处理响应
fmt.Println(resp.StatusCode)
}
- 发送DELETE请求
import (
"fmt"
"net/http"
)
func main() {
url := "http://www.example.com/delete"
req, err := http.NewRequest("DELETE", url, nil)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
// 处理错误
}
defer resp.Body.Close()
// 处理响应
fmt.Println(resp.StatusCode)
}
原文地址: http://www.cveoy.top/t/topic/m0b 著作权归作者所有。请勿转载和采集!