Curl- go的自带包 net/http实现

Curl- go的自带包 net/http实现

case

http包中的Request

发送请求的步骤:1. 创建客户端 2. 发送请求 3. 接受响应

go 复制代码
client :=  &http.Client{}

req, _ := http.NewRequest("POST", url, nil)
// request中有很多参数可以设置

//设置头部
req.Header.set(key,value)


//接受响应
resp,_ := client.Do(req)

http.NewRequest

go 复制代码
// NewRequest wraps NewRequestWithContext using context.Background.
func NewRequest(method, url string, body io.Reader) (*Request, error) {
	return NewRequestWithContext(context.Background(), method, url, body)
}
  • method
    • get,post,delete,put
  • url
  • body :可以是多种形式的数据包含在请求体中

我们可以看出这个 : body是一个io.Reader 所以Request的请求体就是字节流。所以制定编码方式-》用header指定

multipart/form-data 表单方式提交,上传文件

application/x-www-form-urlencoded url编码方式提交

application/json json数据格式提交

go 复制代码
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

接下来就可以往body里放字节流数据

go 复制代码
import uri "net/url"
fromData := uri.Values{}
	for k, v := range data {
		fromData.Set(k, v)
	}
req, _ := http.NewRequest("POST", url, strings.NewReader(fromData.Encode()))

Post Get Delete Put

都可以根据这个模版魔改

复制代码
client :=  &http.Client{}

req, _ := http.NewRequest("POST", url, nil)
// request中有很多参数可以设置

//设置头部
req.Header.set(key,value)


//接受响应
resp,_ := client.Do(req)

例如:from-data的post:

复制代码
func PostWithFromData(url string, headers map[string]string, data map[string]string) []byte {
	jar, _ := cookiejar.New(nil)  // 客户端带cookie,这里没用到
	client := &http.Client{
		Jar: jar,
	}
	fromData := uri.Values{}
	for k, v := range data {
		fromData.Set(k, v)
	}

	req, _ := http.NewRequest("POST", url, strings.NewReader(fromData.Encode()))
	for key, value := range headers {
		req.Header.Set(key, value)
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("发送请求失败:", err)
		return nil
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)

	return body

}
相关推荐
方也_arkling4 小时前
【Java-Day08】static / final / 枚举
java·开发语言
风吹夏回4 小时前
Python 全局异常处理:从“满屏 try-except”到优雅兜底
开发语言·python
Chengbei114 小时前
一站式源码安全检测工具、云安全 / APP / 小程序源码敏感信息递归多层目录扫描AK、JWT、手机号、身份证等敏感信息
java·开发语言·安全·web安全·网络安全·系统安全·安全架构
llz_1124 小时前
web-第一次课后作业
java·开发语言·idea
小熊Coding4 小时前
Python爬取当当网二手图书项目实战!
开发语言·爬虫·python·beautifulsoup·requests·二手图书
秋94 小时前
Java项目运行5天左右自动宕机:系统性定位与解决方案
java·开发语言·python
xiaoshuaishuai85 小时前
C# 内存管理与资源泄漏
开发语言·c#
lsx2024065 小时前
SVN 检出操作
开发语言
鹏北海-RemHusband5 小时前
Go 语言进阶笔记 — 面向 JS/TS 前端开发者
笔记·golang
basketball6166 小时前
C++ NULL 和 nullptr 区别 以及 nullptr 的核心实现
java·开发语言·c++