Use the net/http.Request function to send a customized HTTP request and obtain the response status code and response header
HTTP request is a very common and important communication protocol in modern network communications. In the Go language, we can use the Request function in the net/http package to send HTTP requests, and we can customize various parts of the request. This article will introduce how to use the Request function to send an HTTP request and obtain the response status code and response header.
First, we need to import the net/http package to use the Request function:
import ( "net/http" "fmt" )
Next, we can use the Request function to send HTTP requests. The Request function receives a parameter, which is a Request object, which defines various parts of the request, such as request method, URL, request header, request body, etc. We can customize the request by creating a Request object and setting the corresponding properties.
The following is an example of sending a GET request:
func main() { // 创建Request对象 req, err := http.NewRequest("GET", "http://www.example.com", nil) if err != nil { fmt.Println("创建请求失败:", err) return } // 发送HTTP请求 client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println("发送请求失败:", err) return } // 获取响应状态码 fmt.Println("状态码:", res.StatusCode) // 获取响应头 for key, value := range res.Header { fmt.Println(key, ":", value) } }
In the above example, we create a Request object for a GET request by calling the http.NewRequest function. The parameter "GET" indicates the request method, "http://www.example.com" indicates the request URL, and nil indicates that the request body is empty. We then send the request by calling client.Do(req) and save the returned response in the res variable.
Next, we can get the response status code by calling res.StatusCode. For successful requests, the status code is usually 200; for redirects, server errors, and other situations, the status code will have different values.
Finally, we obtain the response header information by traversing res.Header. The response header is a map, in which the key represents the name of the response header field and the value represents the corresponding value. We can process response headers as needed.
In addition to GET requests, we can also send other types of requests, such as POST, PUT, DELETE, etc. Just set the corresponding request method when creating the Request object.
By using the Request function in the net/http package, we can flexibly send various types of HTTP requests and obtain the response status code and response headers. This gives us greater freedom and flexibility in network communications. I hope the content of this article will be helpful to readers.
The above is the detailed content of Use the net/http.Request function to send a customized HTTP request and obtain the response status code and response headers. For more information, please follow other related articles on the PHP Chinese website!