1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| package main
import ( "fmt" "net/http" "io/ioutil" )
func main() { resp, err := http.Get("https://jsonplaceholder.typicode.com/posts/1") if err != nil { fmt.Println("GET 请求错误:", err) return } defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("读取响应数据错误:", err) return }
fmt.Println("GET 请求响应数据:", string(data))
resp, err = http.Post("https://jsonplaceholder.typicode.com/posts", "application/json", nil) if err != nil { fmt.Println("POST 请求错误:", err) return } defer resp.Body.Close()
data, err = ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("读取响应数据错误:", err) return }
fmt.Println("POST 请求响应数据:", string(data))
req, err := http.NewRequest("PUT", "https://jsonplaceholder.typicode.com/posts/1", nil) if err != nil { fmt.Println("创建 PUT 请求错误:", err) return }
client := &http.Client{} resp, err = client.Do(req) if err != nil { fmt.Println("PUT 请求错误:", err) return } defer resp.Body.Close()
data, err = ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("读取响应数据错误:", err) return }
fmt.Println("PUT 请求响应数据:", string(data))
req, err = http.NewRequest("DELETE", "https://jsonplaceholder.typicode.com/posts/1", nil) if err != nil { fmt.Println("创建 DELETE 请求错误:", err) return }
resp, err = client.Do(req) if err != nil { fmt.Println("DELETE 请求错误:", err) return } defer resp.Body.Close()
data, err = ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("读取响应数据错误:", err) return }
fmt.Println("DELETE 请求响应数据:", string(data)) }
|