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. 硬件设计--DC/DC电源芯片详解

    本文参考:http://www.elecfans.com/article/83/116/2018/20180207631874.html https://blog.csdn.net/wangdapao ...

  2. JAVA面试题 手写ArrayList的实现,在笔试中过关斩将?

    面试官Q1:可以手写一个ArrayList的简单实现吗? 我们都知道ArrayList是基于数组实现,如果让你实现JDK源码ArrayList中add().remove().get()方法,你知道如何 ...

  3. CitusDB Multi-node Install and Test

    Multi-node setup on CentOS 参考官网:https://docs.citusdata.com/en/v6.2/installation/production_rhel.html ...

  4. JWT(JSON WEB TOKEN)实例

    JWT的工具类 加密解密工具 package top.wintp.crud.util; import com.auth0.jwt.JWTSigner; import com.auth0.jwt.JWT ...

  5. Scala数据结构

    Scala数据结构 主要的集合特质 Scala同时支持可变集合和不可变集合,优先采用不可变集合.集合主要分为三大类:序列(List),集(set),映射(map).所有的集合都扩展自Iterable特 ...

  6. DAX 第三篇:过滤器函数

    过滤器函数允许你操纵筛选上下文以创建动态的计算. 一,筛选上下文的构成 DAX中的筛选上下文由三部分构成:交叉过滤构成的过滤,查询上下文中每行的列值构成的过滤,外部切片器构成的显式过滤. 1,交叉过滤 ...

  7. sql注入篇2

    一.前言 上一篇:sql注入篇1 二.基于回显的注入类型判断 1.有结果的注入 例如下图: (sqlllab less-1)可以看到有正常结果返回,对于的利用方式就是老套路了,先order by查询出 ...

  8. IP地址/掩码/网关/DNS的设置与工作原理(转)

    现在互联网飞速发展,工作中生活中上不了网的计算机是不可想象的,而电脑系统网络设置中的IP地址.子网掩码.默认网关及DNS服务器,怎么理解,它们是如何工作的,下面做个简单介绍. 通常的上网方式,是打开I ...

  9. 《VR入门系列教程》之8---GearVR

    高端移动虚拟现实设备---三星GearVR     Oculus Rift也许是虚拟现实头显的典范,但是它还是存在许多问题.首先,它需要基于一个具有强大图形计算能力的计算机,而使用一般的笔记本.苹果A ...

  10. 《VR入门系列教程》之5---应用方向

    VR应用方向     面向消费者的虚拟现实才发展了几年,就出现了大量应用程序,虚拟现实抓住了人们对未来的渴望.开发者甚至想要把整个现实世界都做成虚拟现实,这些都是可以理解的.     但是,现在仍然没 ...