Go语言:发送HTTP请求(GET & POST&NewRequest)

代码示例:

GET&POST列子:
package main

import (
    "bytes"
    "encoding/json"
    "io"
    "io/ioutil"
    "net/http"
    "time"
)

// 发送GET请求
// url:         请求地址
// response:    请求返回的内容
func Get(url string) string {

    // 超时时间:5秒
    client := &http.Client{Timeout: 5 * time.Second}
    resp, err := client.Get(url)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    var buffer [512]byte
    result := bytes.NewBuffer(nil)
    for {
        n, err := resp.Body.Read(buffer[0:])
        result.Write(buffer[0:n])
        if err != nil && err == io.EOF {
            break
        } else if err != nil {
            panic(err)
        }
    }

    return result.String()
}

// 发送POST请求
//func Post(url string, contentType string, body io.Reader) (resp *Response, err error)
// url:         请求地址
// data:        POST请求提交的数据
// contentType: 请求体格式,如:application/json
// body :     请求发送的内容
	//func NewReader(s string) *Reader
	//NewReader:返回一个从s读取的新阅读器(仅支持读)。
	//NewReader:创建一个从s读取数据的Reader(阅读器)。
	//Post:Post向指定的URL发出Post(post请求)
	res, err := http.Post(esRequestUrl, "application/json", strings.NewReader(string(esRequestData)))

	if err != nil {
		log.GLogger.Error(err.Error())
		return nil, err
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)

	if err != nil {
		log.GLogger.Error(err.Error())
		return nil, err
	}
}
log.GLogger.Info("es search url:%v, req:%T, resp:%v", esRequestUrl, esRequestData, string(body))
net/http包没有封装直接使用请求带header的get或者post方法,所以,要想请求中带header或设置cookie(下面列子中有设置cookie的方法),只能使用NewRequest方法(使用该方法时需要先对client实例化:client := &http.Client{})
import (
	"net/http"
	"json"
	"ioutil"
)
type Student struct{
	id string
	name string
}

type StudentReq struct{
	id string
	name string
}
func main() {
	stu := Student{
		id:"2ed4tg5fe35fgty3yy6uh",
		name:"amber",
	}
	stu,err := json.Marshal(&stu)
	reader := bytes.NewReader(stu)
	request,err := http.NewRequest("POST", "http://192.168.1.12:8000/create", reader)
	request.Header.Set("Content-Type", "application/json")
	client:=&http.Client{}
	response,err := client.Do(request)
	defer response.Body.Close()
	body,err := ioutil.ReadAll(response.Body)
	fmt.Printf(string(body))
	
	var stuReq StudentReq 
	err = json.UnMarshal(body, &stuReq)
	fmt.Println(json.MarshalIndent(stuReq))
}

  • stu,err := json.Marshal(&stu):将stu对象改为json格式
  • reader := bytes.NewReader(stu):所以将json改为byte格式,作为body传给http请求
  • request,err := http.NewRequest(“POST”, “http://192.168.1.12:8000/create”, reader):创建url>
  • response,err := client.Do(request):客户端发起请求,接收返回值
  • body,err := ioutil.ReadAll(response.Body):读取body的值,返回类型是byte
  • json.MarshalIndent(stuReq):修改json为标准格式
http.Clicent:是一个HTTP客户端,客户机比往返器(比如传输)更高级,还处理HTTP细节,比如cookie,重定向,长连接。
func httpDo() {
// http.Clicent:是一个HTTP客户端,客户机比往返器(比如传输)更高级,还处理HTTP细节,比如cookie,重定向,长连接。
    client := &http.Client{}
 // 使用 NewRequest 设置头参数、cookie之类的数据,
     req, err := http.NewRequest("POST", "http://www.01happy.com/demo/accept.php", strings.NewReader("name=cjb"))
    if err != nil {
        // handle error
    }

    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    req.Header.Set("Cookie", "name=anny")

    resp, err := client.Do(req)

    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }

    fmt.Println(string(body))
}

未完待续~

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值