使用 golang 中的 net/http 包来发送和接收 http 请求

开启 web server

先实现一个简单的 http server,用来接收请求

package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
) func IndexHandler(w http.ResponseWriter, r *http.Request){
//打印请求主机地址
fmt.Println(r.Host)
//打印请求头信息
fmt.Printf("header content:[%v]\n", r.Header) //获取 post 请求中 form 里边的数据
fmt.Printf("form content:[%s, %s]\n", r.PostFormValue("username"), r.PostFormValue("passwd")) //读取请求体信息
bodyContent, err := ioutil.ReadAll(r.Body)
if err != nil && err != io.EOF {
fmt.Printf("read body content failed, err:[%s]\n", err.Error())
return
}
fmt.Printf("body content:[%s]\n", string(bodyContent)) //返回响应内容
fmt.Fprintf(w, "hello world ~")
} func main (){
http.HandleFunc("/index", IndexHandler)
http.ListenAndServe("10.10.19.200:8000", nil)
}

发送 GET 请求

最基本的GET请求

package main
import (
"fmt"
"io/ioutil"
"net/http"
) func httpGet(url string) (err error) {
resp, err := http.Get(url)
if err != nil {
fmt.Printf("get request failed, err:[%s]", err.Error())
return
}
defer resp.Body.Close() bodyContent, err := ioutil.ReadAll(resp.Body)
fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
fmt.Printf("resp body data:[%s]\n", string(bodyContent))
return
} func main() {
var url = "http://10.10.19.200:8000/index"
httpGet(url)
}

带参数的 GET 请求

1)在 url 后面携带参数

package main
import (
"fmt"
"io/ioutil"
"net/http"
) func httpGet(url string) (err error) {
resp, err := http.Get(url)
if err != nil {
fmt.Printf("get request failed, err:[%s]", err.Error())
return
}
defer resp.Body.Close() bodyContent, err := ioutil.ReadAll(resp.Body)
fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
fmt.Printf("resp body data:[%s]\n", string(bodyContent))
return
} func main() {
var url = "http://10.10.19.200:8000/index?query=googlesearch"
httpGet(url)
}

2)如果想要把一些参数做成变量,然后放到 url 中,可以参考下面的方式

package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
) func httpGet(requestUrl string) (err error) {
Url, err := url.Parse(requestUrl)
if err != nil {
fmt.Printf("requestUrl parse failed, err:[%s]", err.Error())
return
} params := url.Values{}
params.Set("query","googlesearch")
params.Set("content","golang")
Url.RawQuery = params.Encode() requestUrl = Url.String()
fmt.Printf("requestUrl:[%s]\n", requestUrl) resp, err := http.Get(requestUrl)
if err != nil {
fmt.Printf("get request failed, err:[%s]", err.Error())
return
}
defer resp.Body.Close() bodyContent, err := ioutil.ReadAll(resp.Body)
fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
fmt.Printf("resp body data:[%s]\n", string(bodyContent))
return
} func main() {
var url = "http://10.10.19.200:8000/index"
httpGet(url)
}

运行结果:

requestUrl:[http://10.10.19.200:8000/index?content=golang&query=googlesearch]
resp status code:[200]
resp body data:[hello world ~]

GET 请求添加请求头

package main

import (
"fmt"
"io/ioutil"
"net/http"
) func httpGet(requestUrl string) (err error) {
client := &http.Client{}
requestGet, _:= http.NewRequest("GET", requestUrl, nil) requestGet.Header.Add("query", "googlesearch")
requestGet.Header.Add("content", "golang") resp, err := client.Do(requestGet)
if err != nil {
fmt.Printf("get request failed, err:[%s]", err.Error())
return
}
defer resp.Body.Close() bodyContent, err := ioutil.ReadAll(resp.Body)
fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
fmt.Printf("resp body data:[%s]\n", string(bodyContent))
return
} func main() {
var url = "http://10.10.19.200:8000/index"
httpGet(url)
}

从 http server 端可以看到设置的请求头数据:

type:[http.Header], header content:[map[Accept-Encoding:[gzip] Content:[golang] Query:[googlesearch] User-Agent:[Go-http-client/1.1]]]

发送 POST 请求

发送 form 表单格式的 post 请求

package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
) func httpPost(requestUrl string) (err error) {
data := url.Values{}
data.Add("username", "seemmo")
data.Add("passwd", "da123qwe") resp, err := http.PostForm(requestUrl, data)
if err != nil {
fmt.Printf("get request failed, err:[%s]", err.Error())
return
}
defer resp.Body.Close() bodyContent, err := ioutil.ReadAll(resp.Body)
fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
fmt.Printf("resp body data:[%s]\n", string(bodyContent))
return
} func main() {
var url = "http://10.10.19.200:8000/index"
httpPost(url)
}

发送 json 格式的 post 请求

1)使用 http.Client

下面的请求中没有携带请求头 Content-Type

package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
) func httpPost(requestUrl string) (err error) {
client := &http.Client{} data := make(map[string]interface{})
data["name"] = "seemmo"
data["passwd"] = "da123qwe"
jsonData, _ := json.Marshal(data) requestPost, err := http.NewRequest("POST", requestUrl, bytes.NewReader(jsonData))
resp, err := client.Do(requestPost)
if err != nil {
fmt.Printf("get request failed, err:[%s]", err.Error())
return
}
defer resp.Body.Close() bodyContent, err := ioutil.ReadAll(resp.Body)
fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
fmt.Printf("resp body data:[%s]\n", string(bodyContent))
return
} func main() {
var url = "http://10.10.19.200:8000/index"
httpPost(url)
}

2)使用 http.Post

package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
) func httpPost(requestUrl string) (err error) {
data := make(map[string]interface{})
data["name"] = "seemmo"
data["passwd"] = "da123qwe"
jsonData, _ := json.Marshal(data) resp, err := http.Post(requestUrl, "application/json", bytes.NewReader(jsonData))
if err != nil {
fmt.Printf("get request failed, err:[%s]", err.Error())
return
}
defer resp.Body.Close() bodyContent, err := ioutil.ReadAll(resp.Body)
fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
fmt.Printf("resp body data:[%s]\n", string(bodyContent))
return
} func main() {
var url = "http://10.10.19.200:8000/index"
httpPost(url)
}

参考链接:https://www.cnblogs.com/zhaof/p/11346412.html

ending~

Go net/http 发送常见的 http 请求的更多相关文章

  1. java常见的 http 请求库比较

    java常见的http请求库有httpclient,RestTemplate,OKhttp,更高层次封装的 feign.retrofit 1.HttpClient HttpClient:代码复杂,还得 ...

  2. (七)四种常见的post请求中的参数形式

    原文链接:https://blog.csdn.net/jiadajing267/article/details/87883725 1).HTTP 协议是以 ASCII 码 传输,建立在 TCP/IP ...

  3. [转]利用URLConnection来发送POST和GET请求

    URL的openConnection()方法将返回一个URLConnection对象,该对象表示应用程序和 URL 之间的通信链接.程序可以通过URLConnection实例向该URL发送请求.读取U ...

  4. 在C#用HttpWebRequest中发送GET/HTTP/HTTPS请求

    通用辅助类  下面是我编写的一个辅助类,在这个类中采用了HttpWebRequest中发送GET/HTTP/HTTPS请求,因为有的时候需 要获取认证信息(如Cookie),所以返回的是HttpWeb ...

  5. (转) 在C#用HttpWebRequest中发送GET/HTTP/HTTPS请求

    转自:http://blog.csdn.net/zhoufoxcn/article/details/6404236 通用辅助类 下面是我编写的一个辅助类,在这个类中采用了HttpWebRequest中 ...

  6. iOS开发网络篇—发送GET和POST请求(使用NSURLSession)

    iOS开发网络篇—发送GET和POST请求(使用NSURLSession) 说明: 1)该文主要介绍如何使用NSURLSession来发送GET请求和POST请求 2)本文将不再讲解NSURLConn ...

  7. Ajax详解及其案例分析------如何获得Ajax对象,使用Ajax对象发送GET和POST请求,校验用户名,POST和GET请求时的乱码处理,实现级联的下拉列表

    本节主要内容预览: 1 获得Ajax对象 2 使用Ajax对象发送GET请求 3 使用Ajax对象发送POST请求 4 使用Ajax校验用户名 5 POST请求时的乱码处理 6 GET请求时的乱码处理 ...

  8. php 利用socket发送GET,POST请求

    作为php程序员一定会接触http协议,也只有深入了解http协议,编程水平才会更进一步.最近我一直在学习php的关于http的编程,许多东西恍然大悟,受益匪浅.希望分享给大家.本文需要有一定http ...

  9. 【转】在C#用HttpWebRequest中发送GET/HTTP/HTTPS请求

    http://zhoufoxcn.blog.51cto.com/792419/561934 这个需求来自于我最近练手的一个项目,在项目中我需要将一些自己发表的和收藏整理的网文集中到一个地方存放,如果全 ...

随机推荐

  1. Quartz Configuration Reference

    Quartz Configuration Reference Choose a topic: Main Configuration (configuration of primary schedule ...

  2. Docs-.NET-C#-指南-语言参考-关键字-值类型-:浮点数值类型

    ylbtech-Docs-.NET-C#-指南-语言参考-关键字-值类型-:浮点数值类型 1.返回顶部 1. 浮点数值类型(C# 引用) 2019/10/22 “浮点类型”是“简单类型”的子集,可以使 ...

  3. centos7设置rsyslog日志服务集中服务器

    centos7设置rsyslog日志服务集中服务器 环境:centos6.9_x86_64,自带的rsyslog版本是7.4.7,很多配置都不支持,于是进行升级后配置 # 安装新版本的rsyslog程 ...

  4. C++17 std::shared_mutex的替代方案boost::shared_mutex

    C++17 std::shared_mutex的替代方案boost::shared_mutex C++17boost  std::shared_mutex http://en.cppreference ...

  5. 一行命令学会全基因组关联分析(GWAS)的meta分析

    为什么需要做meta分析 群体分层是GWAS研究中一个比较常见的假阳性来源. 也就是说,如果数据存在群体分层,却不加以控制,那么很容易得到一堆假阳性位点. 当群体出现分层时,常规手段就是将分层的群体独 ...

  6. Siamese Net

    参考博客:https://blog.csdn.net/ybdesire/article/details/84072339

  7. 【serviceaccount 和 clusterrolebinding】

    kubectl get clusterrolebinding kubectl create clusterrolebinding suosheng-rebinding --clusterrole=cl ...

  8. HTML布局排版之制作个人网站的文章列表

    文章列表.博文列表,一般是有文章名字和时间构成的,文章名字后面是时间,点击文章的名字,可进入该文章.为了美观,一般文章名字都有一定的最大字数限制,长宽对齐,等长宽的统一格式比较美观,这种用表格来做比较 ...

  9. c#写windows服务 小demo

    前段时间做一个数据迁移项目,刚开始用B/S架构做的项目,但B/S要寄存在IIs中,而IIs又不稳定因素,如果重启IIs就要打开页面才能运行项目.有不便之处,就改用Windows服务实现.这篇就总结下, ...

  10. MYSQL 递归操作

    MYSQL 递归? ===================== 表: t_node node_id int node_name varchar2(45) parent_id int       级, ...