Go语言-基本的http请求操作
Go发起GET请求
基本的GET请求
//基本的GET请求
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("http://www.hao123.com")
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
fmt.Println(resp.StatusCode)
if resp.StatusCode == 200 {
fmt.Println("ok")
}
}
带参数的GET请求
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main(){
resp, err := http.Get("http://www.baidu.com?name=Paul_Chan&age=26")
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
如果我们想要把一些参数做成变量而不是直接放到url中怎么操作,代码例子如下:
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
func main(){
params := url.Values{}
Url, err := url.Parse("http://www.baidu.com")
if err != nil {
return
}
params.Set("name","Paul_Chan")
params.Set("age","26")
//如果参数中有中文参数,这个方法会进行URLEncode
Url.RawQuery = params.Encode()
urlPath := Url.String()
fmt.Println(urlPath) // https://www.baidu.com?age=26&name=Paul_chan
resp,err := http.Get(urlPath)
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
解析JSON类型的返回结果
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type result struct {
Args string `json:"args"`
Headers map[string]string `json:"headers"`
Origin string `json:"origin"`
Url string `json:"url"`
}
func main() {
resp, err := http.Get("http://xxx.com")
if err != nil {
return
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
var res result
_ = json.Unmarshal(body,&res)
fmt.Printf("%#v", res)
}
GET请求添加请求头
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
client := &http.Client{}
req,_ := http.NewRequest("GET","http://xxx.com",nil)
req.Header.Add("name","Paul_Chan")
req.Header.Add("age","26")
resp,_ := client.Do(req)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Printf(string(body))
}
从上述的结果可以看出我们设置的头是成功了:
{
"args": {},
"headers": {
"Accept-Encoding": "gzip",
"Age": "26",
"Host": "xxx.com",
"Name": "Paul_Chan",
"User-Agent": "Go-http-client/1.1"
},
"origin": "211.138.20.170, 211.138.20.170",
"url": "https://xxx.com"
}
golang 发起POST请求
基本的POST使用
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
func main() {
urlValues := url.Values{}
urlValues.Add("name","Paul_Chan")
urlValues.Add("age","26")
resp, _ := http.PostForm("http://xxx.com/post",urlValues)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
//结果如下:
/******************
{
"args": {},
"data": "",
"files": {},
"form": {
"age": "26",
"name": "Paul_Chan"
},
"headers": {
"Accept-Encoding": "gzip",
"Content-Length": "19",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Go-http-client/1.1"
},
"json": null,
"origin": "211.138.20.170, 211.138.20.170",
"url": "https://httpbin.org/post"
}
******************/
另外一种方式
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
func main() {
urlValues := url.Values{
"name":{"Paul_Chan"},
"age":{"26"},
}
reqBody:= urlValues.Encode()
resp, _ := http.Post("http://xxx.com/post", "text/html",strings.NewReader(reqBody))
body,_:= ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
//结果如下:
/**************
{
"args": {},
"data": "age=26&name=Paul_Chan",
"files": {},
"form": {},
"headers": {
"Accept-Encoding": "gzip",
"Content-Length": "19",
"Content-Type": "text/html",
"Host": "httpbin.org",
"User-Agent": "Go-http-client/1.1"
},
"json": null,
"origin": "211.138.20.170, 211.138.20.170",
"url": "https://httpbin.org/post"
}
***************/
发送JSON数据的post请求
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
client := &http.Client{}
data := make(map[string]interface{})
data["name"] = "zhaofan"
data["age"] = "23"
bytesData, _ := json.Marshal(data)
req, _ := http.NewRequest("POST","http://httpbin.org/post",bytes.NewReader(bytesData))
resp, _ := client.Do(req)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
//结果如下:
/*************
{
"args": {},
"data": "{\"age\":\"23\",\"name\":\"zhaofan\"}",
"files": {},
"form": {},
"headers": {
"Accept-Encoding": "gzip",
"Content-Length": "29",
"Host": "httpbin.org",
"User-Agent": "Go-http-client/1.1"
},
"json": {
"age": "23",
"name": "zhaofan"
},
"origin": "211.138.20.170, 211.138.20.170",
"url": "https://httpbin.org/post"
}
*************/
不用client的post请求
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
data := make(map[string]interface{})
data["name"] = "zhaofan"
data["age"] = "23"
bytesData, _ := json.Marshal(data)
resp, _ := http.Post("http://httpbin.org/post","application/json", bytes.NewReader(bytesData))
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
做任何事情,都要以创业的心态去干!
Go语言-基本的http请求操作的更多相关文章
- Win8开虚拟wifi ‘无法启动承载网络 组或资源的状态不是执行请求操作的正确状态“
第一步,首先我们点开开始按钮菜单,要右键以“管理员身份”打开CMD“命令提示符”并键入或者复制(粘贴)命令:netsh wlan show drivers 查看本机无线网卡是否支持此项Wifi热点共享 ...
- YTU 2974: C语言习题5.26--文件操作3
2974: C语言习题5.26--文件操作3 时间限制: 1 Sec 内存限制: 128 MB 提交: 213 解决: 92 题目描述 文本文件score.dic 中存储了n名学生的信息(班级编号 ...
- YTU 2973: C语言习题5.25--文件操作2
2973: C语言习题5.25--文件操作2 时间限制: 1 Sec 内存限制: 128 MB 提交: 242 解决: 105 题目描述 文本文件score.dic 中存储了n名学生的信息(班级编 ...
- YTU 2972: C语言习题5.24--文件操作1
2972: C语言习题5.24--文件操作1 时间限制: 1 Sec 内存限制: 128 MB 提交: 248 解决: 94 题目描述 文本文件score.dic 中存储了n名学生的信息(班级编号 ...
- C语言对mysql数据库的操作
原文:C语言对mysql数据库的操作 这已经是一相当老的话题.不过今天我才首次使用,把今天的一些体会写下来,也许能给一些新手带来一定的帮助,更重要的是供自己今后忘记的怎么使用而进行查阅的! 我们言归正 ...
- 使用c语言实现linux数据库的操作
前言:上一篇讲解了linux下使用命令行操作数据库,这篇继续讲解怎么使用c语言实现linux数据库的操作. 使用c语言实现环境搭建:既然我们要使用c语言实现linux数据库操作,那么首先我们得先把数据 ...
- 【转】python3 urllib.request 网络请求操作
python3 urllib.request 网络请求操作 基本的网络请求示例 ''' Created on 2014年4月22日 @author: dev.keke@gmail.com ''' im ...
- 假定某系统提供硬件的访管指令(例如形式:“svc n”),为了实现系统调用,系统设计者应做哪些工作?用户又如如何请求操作系统服务?
工作: 1. 编写并调试好能实现各种功能的例行子程序. 2. 编写并调试好访管中断处理程序. 3. 构造例行子程序入口地址表. 在用户程序中,需要请求操作系统服务的地方安排一条系统调用.这样,当 ...
- 在Go语言中基础的Redis操作
在Go语言中基础的Redis操作 需要先安装redigo go get "github.com/garyburd/redigo/redis" Go语言Redis客户端的简单示例 连 ...
随机推荐
- STM32F072从零配置工程-串口USART配置
也是使用HAL库进行配置,通过STMCube生成代码,可以通过这个简单的配置过程看到STMCube生成代码的一种规范: 从main函数入手观察其外设配置结构: 首先是HAL_Init()进行所有外设的 ...
- MyBatis从入门到精通:使用XML方式(映射文件之类的)
2.3节笔记部分: package tk.mybatis.simple; public class Temp { } /* 2.2 使用XML方式 MyBatis使用了Java的动态代理可以直接通过接 ...
- 码云及Git的使用
什么是码云 码云就是相当一个远程仓库,在以后的工作中,你和同事负责工作的不同部分,齐头并进,最后上传到码云,类似于一个汇总的作用. 同一个绳上的不同分支 码云网址链接:https://gitee.co ...
- exgcd、二元一次不定方程学习笔记
(不会LATEX,只好用Word) ( QwQ数论好难) 再补充一点,单次询问a,b求逆元的题可以直接化简然后套用exgcd求解. 例题:https://www.luogu.org/problemne ...
- UVA-10608 Friends 【并查集】
There is a town with N citizens. It is known that some pairs of people are friends. According to the ...
- 第一届合天杯河北科技大学网络安全技术大赛 web6 writeup
- HBase部署与使用
HBase部署与使用 概述 HBase的角色 HMaster 功能: 监控RegionServer 处理RegionServer故障转移 处理元数据的变更 处理region的分配或移除 在空闲时间进行 ...
- TensorFlow笔记-模型的保存,恢复,实现线性回归
模型的保存 tf.train.Saver(var_list=None,max_to_keep=5) •var_list:指定将要保存和还原的变量.它可以作为一个 dict或一个列表传递. •max_t ...
- C#2.0新增功能03 匿名方法
连载目录 [已更新最新开发文章,点击查看详细] 在 2.0 之前的 C# 版本中,声明委托的唯一方式是使用命名方法. C# 2.0 引入匿名方法,在 C# 3.0 及更高版本中,Lambda 表 ...
- 一文了解有趣的位运算(&、|、^、~、>>、<<)
1.位运算概述 从现代计算机中所有的数据二进制的形式存储在设备中.即0.1两种状态,计算机对二进制数据进行的运算(+.-.*./)都是叫位运算,即将符号位共同参与运算的运算. 口说无凭,举一个简单的例 ...