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请求操作的更多相关文章

  1. Win8开虚拟wifi ‘无法启动承载网络 组或资源的状态不是执行请求操作的正确状态“

    第一步,首先我们点开开始按钮菜单,要右键以“管理员身份”打开CMD“命令提示符”并键入或者复制(粘贴)命令:netsh wlan show drivers 查看本机无线网卡是否支持此项Wifi热点共享 ...

  2. YTU 2974: C语言习题5.26--文件操作3

    2974: C语言习题5.26--文件操作3 时间限制: 1 Sec  内存限制: 128 MB 提交: 213  解决: 92 题目描述 文本文件score.dic 中存储了n名学生的信息(班级编号 ...

  3. YTU 2973: C语言习题5.25--文件操作2

    2973: C语言习题5.25--文件操作2 时间限制: 1 Sec  内存限制: 128 MB 提交: 242  解决: 105 题目描述 文本文件score.dic 中存储了n名学生的信息(班级编 ...

  4. YTU 2972: C语言习题5.24--文件操作1

    2972: C语言习题5.24--文件操作1 时间限制: 1 Sec  内存限制: 128 MB 提交: 248  解决: 94 题目描述 文本文件score.dic 中存储了n名学生的信息(班级编号 ...

  5. C语言对mysql数据库的操作

    原文:C语言对mysql数据库的操作 这已经是一相当老的话题.不过今天我才首次使用,把今天的一些体会写下来,也许能给一些新手带来一定的帮助,更重要的是供自己今后忘记的怎么使用而进行查阅的! 我们言归正 ...

  6. 使用c语言实现linux数据库的操作

    前言:上一篇讲解了linux下使用命令行操作数据库,这篇继续讲解怎么使用c语言实现linux数据库的操作. 使用c语言实现环境搭建:既然我们要使用c语言实现linux数据库操作,那么首先我们得先把数据 ...

  7. 【转】python3 urllib.request 网络请求操作

    python3 urllib.request 网络请求操作 基本的网络请求示例 ''' Created on 2014年4月22日 @author: dev.keke@gmail.com ''' im ...

  8. 假定某系统提供硬件的访管指令(例如形式:“svc n”),为了实现系统调用,系统设计者应做哪些工作?用户又如如何请求操作系统服务?

    工作: 1.  编写并调试好能实现各种功能的例行子程序. 2.  编写并调试好访管中断处理程序. 3.  构造例行子程序入口地址表. 在用户程序中,需要请求操作系统服务的地方安排一条系统调用.这样,当 ...

  9. 在Go语言中基础的Redis操作

    在Go语言中基础的Redis操作 需要先安装redigo go get "github.com/garyburd/redigo/redis" Go语言Redis客户端的简单示例 连 ...

随机推荐

  1. 【深入浅出-JVM】(8):TLAB

    概念 TLAB(Thread Local Allocation Buffer)线程本地分配缓冲区(线程私有分配区,私有分配,公共查看),占用 Eden 区(缺省 Eden 的1%),默认开启,JVM ...

  2. Jquery serialize()提交多个表单数据

    ajax提交多个表单数据: 先把不同的表单分别用serialize()函数,然后把序列化后的数据用+拼接提交给后台,具体例子如下 var data1 = $('#form1).serialize(); ...

  3. ZIP:ZipFile

    ZipFile: /* 此类用于从 ZIP 文件读取条目 */ ZipFile(File file) :打开供阅读的 ZIP 文件,由指定的 File 对象给出. ZipFile(File file, ...

  4. ASP.NET--Web服务器端控件和Html控件

    今天学习总结了一些相关概念和知识. 之前无论是做 单机的winform 还是 CS的winform 感觉,不到两年下来感觉还可以,虽然API有很多,但是还是比较熟悉基于WINDOWS消息机制的编程,但 ...

  5. Hive的基本操作和数据类型

    Hive的基本操作 1.启动Hive bin/hive 2.查看数据库 hive>show databases; 3. 打开默认数据库 hive>use default; 4.显示defa ...

  6. [剑指offer] 34. 第一个只出现一次的字符

    题目描述 在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写). 一次遍历存储到哈希表 一次 ...

  7. IT界的复仇者联盟解读

    漫威宇宙应用到IT界也是可以解读的,自从编程语言分了派系后,故事就多了,今天我们就用漫威宇宙的故事来解读一下IT界的故事. 漫威宇宙其实也就讲了一件事,整个宇宙就好比一个Java项目,其中有一群叫做美 ...

  8. <表格>

    一.列表 信息资源的一种展示形式 二.列表的分类 1.有序列表 <ol> <li>列表项1</li> <li>列表项2</li> </ ...

  9. java多线程核心api以及相关概念(一)

    这篇博客总结了对线程核心api以及相关概念的学习,黑体字可以理解为重点,其他的都是我对它的理解 个人认为这些是学习java多线程的基础,不理解熟悉这些,后面的也不可能学好滴 目录 1.什么是线程以及优 ...

  10. Linux升级GCC

    升级原因 测试需要使用DOClever,下载了最新的node8.11,运行node 时候报错 [root@app_test bin]# node www module.js:681 return pr ...