首页 > 其他分享 >第六篇: http库

第六篇: http库

时间:2022-10-03 03:56:37浏览次数:47  
标签:http err nil fmt Println return 第六篇

Go-http---post请求

package main

import (
	"fmt"
	"strings"
	"net/http"
	"io/ioutil"
)

func main() {

	url := "http://127.0.0.1:8080/api/v1/login"
	method := "POST"

	payload := strings.NewReader(`{
    "userid":94372175745650688,
    "password":"admin123"
}`)

	client := &http.Client {
	}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Println(err)
		return
	}
	req.Header.Add("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(body))
}

Go-http---get请求

package main

import (
  "fmt"
  "net/http"
  "io/ioutil"
)

func main() {

  url := "http://127.0.0.1:8080/api/v1/get_id/?userid=94372175745650688"
  method := "GET"

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, nil)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjk0MzcyMTc1NzQ1NjUwNjg4LCJleHAiOjE2MTY3Mzg0NzYsImlzcyI6ImJsdWViZWxsLWplZmYifQ.R5kJQZZzu2Ksv9YM6H-Ko46J2C9BBG7t3YcjWq81_94")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}

标签:http,err,nil,fmt,Println,return,第六篇
From: https://www.cnblogs.com/l-uz/p/16749900.html

相关文章