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客户端的简单示例 连 ...
随机推荐
- 20131207-ADO.NET-第十六天
[1]快捷键 工具箱:ctrl+w+x 首字母定位控件范围 属性:F4 或ctrl+w+p Tab跳转 ,home 与end也有效 [2]连接字符串 string str = "Data S ...
- CSS Grid网格布局全攻略
CSS Grid网格布局全攻略 所有奇技淫巧都只在方寸之间. 几乎从我们踏入前端开发这个领域开始,就不停地接触不同的布局技术.从常见的浮动到表格布局,再到如今大行其道的flex布局,css布局技术一直 ...
- C# Winform --xml文件
背景: 在工作中,学习和使用OPC Server/Client系统时,发现开发的设计结构是把设备PLC的TAGLIST写为XML文件,在程序启动的时候载入从而完成自动配置. 从而开始了C# ASP.N ...
- Spring Boot 整合 Shiro实现认证及授权管理
Spring Boot Shiro 本示例要内容 基于RBAC,授权.认证 加密.解密 统一异常处理 redis session支持 介绍 Apache Shiro 是一个功能强大且易于使用的Java ...
- vijos p1217 乒乓球
注意数组越界.#include<iostream> #include<cmath> using namespace std; char letter[10001]; void ...
- nginx配置目录访问&用户名密码控制
背景 项目上需要一些共享目录让外地同事可以网页访问对应的文件,且受权限控制: 现有环境: centos nginx 你可以了解到以下内容: 配置nginx开启目录访问 并配置nginx用户名和密码进行 ...
- hdu6406 Taotao Picks Apples(线段树)
Taotao Picks Apples 题目传送门 解题思路 建立一颗线段树,维护当前区间内的最大值maxx和可摘取的苹果数num.最大值很容易维护,主要是可摘取的苹果数怎么合并.合并左右孩子时,左孩 ...
- 【微信小程序】微信小程序-实现tab
一.前言 小程序开发中,有很多封装好的控件供开发者使用,但是,很常见的tab选项卡居然没有,只能自己搞一个. 实现原理也很简单,无非是用给view(tab)设置一个点击事件bintap,并且给view ...
- T-SQL 镜像测试
--====================================================== ----镜像计划建立 2016-05-10 17:05:16.463 hubiyun ...
- PAY8 数字货币支付结算系统,全球付!实时结算!秒到账!
数字货币支付是历史发展的必然 如今已经有越来越多的地方接受加密数字货币作为支付消费了,比如泰国电影院连锁店 Cineplex Group 可用加密货币买爆米花和电影票,西班牙一精品酒店接受数字货币支付 ...