目录
前言
queryheaderPOST
POST 请求
HTTPPOSTjsonbodyjsonRestFul APIHTTPPOSTjsonbody
import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" ) type User struct { Username string `json:"username"` Password string `json:"password"` } func main() { client := http.Client{} user := User{ Username: "123456", Password: "12346", } dataByte, err := json.Marshal(user) if err != nil { fmt.Println(err) } bodyReader := bytes.NewReader(dataByte) request, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "http://localhost:8080/user", bodyReader) if err != nil { return } request.Header.Set("Content-Type", "application/json") resp, err := client.Do(request) if err != nil { fmt.Println(err) return } fmt.Println("statusCode: ", resp.StatusCode) body, err := io.ReadAll(resp.Body) if err != nil { return } defer resp.Body.Close() fmt.Println(string(body)) }
Userjson.Marshaluser[]bytebytes.NewReader[]byteReaderhttp.NewRequestWithContextbodyReaderuserReaderjsonbodyContent-Typeapplication/json
application/x-www-form-urlencodedbody
values := url.Values{} values.Set("username", "1234") values.Set("password", "1234") bodyReader := strings.NewReader(values.Encode())
小结
POSTjsonapplication/x-www-form-urlencodedbodyHTTPquerybodyGETPOSTPUTDELETENewRequestWithContexthttp.MethodPuthttp.MethodDelete
您可能感兴趣的文章: