当前位置: 首页 > news >正文

golang 发送GET和POST示例

GET请求

get请求可以直接使用 http.Get方法
简单
func main(){
resp, err := http.Get("https://baidu.com")
    if err != nil {
        panic(err)
    
    }
    defer resp.Body.Close()
    s,err:=ioutil.ReadAll(resp.Body)
    fmt.Printf(string(s))
}
复杂
func main() {

    params := url.Values{}

    Url, err := url.Parse("http://baidu.com?fd=fdsf")
    if err != nil {
        panic(err.Error())

    }
    params.Set("a", "fdfds")
    params.Set("id", string("1"))
    //如果参数中有中文参数,这个方法会进行URLEncode
    Url.RawQuery = params.Encode()
    urlPath := Url.String()
    resp, err := http.Get(urlPath)
    defer resp.Body.Close()
    s, err := ioutil.ReadAll(resp.Body)
    fmt.Println(string(s))

}

这个params.set是不是感觉跟php里的http_build_query,自己感觉哈

POST 请求

使用 http.post
type Server struct {
    ServerName string
    ServerIp   string
}

type ServerSlice struct {
    Server    []Server
    ServersID string
}

func main() {
    //post 第三个参数是io.reader interface
    //strings.NewReader  byte.NewReader bytes.NewBuffer  实现了read 方法
    s := ServerSlice{ServersID: "tearm", Server: []Server{{"beijing", "127.0.0.1"}, {"shanghai", "127.0.0.1"}}}
    b, _ := json.Marshal(s)
         fmt.Println(string(b))
    resp, _ := http.Post("http://baidu.com", "application/x-www-form-urlencoded", strings.NewReader("heel="+string(b)))
    //
    defer resp.Body.Close()
    //io.Reader

    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
使用 http.PostForm
func httpPostForm() {
// params:=url.Values{}
// params.Set("hello","fdsfs")  //这两种都可以
   params= url.Values{"key": {"Value"}, "id": {"123"}}
     resp, _:= http.PostForm("http://baidu.com",
       body)
 
    defer resp.Body.Close()
    body, _:= ioutil.ReadAll(resp.Body)
    
    fmt.Println(string(body))
 
}

如果需要设置头参数,cookie之类的数据,就可以使用http.Do

func httpDo() {
    client := &http.Client{}
    
    req, err := http.NewRequest("POST", "baidu.com", 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))
}

同样的http.NewRequest第三个参数只需要实现io.reader接口就行

相关文章:

  • 监听器
  • 用Hexo搭建属于自己的Blog
  • ipcs命令详解
  • 多态
  • 个人站点的日期查询
  • 2017-2018年度Scrum现状报告发布
  • 我们的春节--2019
  • BZOJ 1412 狼和羊的故事
  • LeetCode29.两数相除 JavaScript
  • vim命令模式下光标移动+查找
  • Fastjson的基本使用方法大全
  • 面孔相册按脸给照片分类 这是靠小米人脸检测技术实现的
  • 数据结构java版之冒泡排序及优化
  • 洛谷1474货币系统——小心重复的完全背包
  • 博弈论入门之斐波那契博弈
  • [分享]iOS开发-关于在xcode中引用文件夹右边出现问号的解决办法
  • “大数据应用场景”之隔壁老王(连载四)
  • 《Java编程思想》读书笔记-对象导论
  • co.js - 让异步代码同步化
  • Git学习与使用心得(1)—— 初始化
  • HTTP中GET与POST的区别 99%的错误认识
  • JAVA之继承和多态
  • js算法-归并排序(merge_sort)
  • Leetcode 27 Remove Element
  • 给第三方使用接口的 URL 签名实现
  • 前端每日实战 2018 年 7 月份项目汇总(共 29 个项目)
  • 前端学习笔记之原型——一张图说明`prototype`和`__proto__`的区别
  • 学习笔记DL002:AI、机器学习、表示学习、深度学习,第一次大衰退
  • 中文输入法与React文本输入框的问题与解决方案
  • 蚂蚁金服CTO程立:真正的技术革命才刚刚开始
  • ​力扣解法汇总1802. 有界数组中指定下标处的最大值
  • ​软考-高级-信息系统项目管理师教程 第四版【第23章-组织通用管理-思维导图】​
  • (02)vite环境变量配置
  • (Redis使用系列) Springboot 使用redis的List数据结构实现简单的排队功能场景 九
  • (待修改)PyG安装步骤
  • (详细版)Vary: Scaling up the Vision Vocabulary for Large Vision-Language Models
  • (转)socket Aio demo
  • (转)使用VMware vSphere标准交换机设置网络连接
  • (转载)跟我一起学习VIM - The Life Changing Editor
  • .bat批处理(二):%0 %1——给批处理脚本传递参数
  • .Net 4.0并行库实用性演练
  • .net mvc 获取url中controller和action
  • .NET 中小心嵌套等待的 Task,它可能会耗尽你线程池的现有资源,出现类似死锁的情况
  • .NET/C# 使用 SpanT 为字符串处理提升性能
  • .NET3.5下用Lambda简化跨线程访问窗体控件,避免繁复的delegate,Invoke(转)
  • .net6+aspose.words导出word并转pdf
  • .NetCore 如何动态路由
  • .net利用SQLBulkCopy进行数据库之间的大批量数据传递
  • .w文件怎么转成html文件,使用pandoc进行Word与Markdown文件转化
  • /usr/local/nginx/logs/nginx.pid failed (2: No such file or directory)
  • @NestedConfigurationProperty 注解用法
  • @SpringBootApplication 包含的三个注解及其含义
  • []T 还是 []*T, 这是一个问题
  • [<事务专题>]
  • [3D游戏开发实践] Cocos Cyberpunk 源码解读-高中低端机性能适配策略