• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

http标准库客户端功能

武飞扬头像
学的像个弟弟
帮助1

1.发出GET请求

func TestGet1() {
	//http://apis.juhe.cn/simpleWeather/query 是 接口地址
	//key=b464cc38b226061e79adcf6b722b0e54 是 请求 key
	url := "http://apis.juhe.cn/simpleWeather/query?city=深圳&key=b464cc38b226061e79adcf6b722b0e54"
	//url := "https://www.百度.com/"
	//Request
	r, err := http.Get(url)
	if err != nil {
		//使用 log.Fatal()函数在控制台屏幕上打印带有时间戳的指定消息
		log.Fatal(err)
	}
	defer r.Body.Close()
	b, _ := ioutil.ReadAll(r.Body)
	fmt.Printf("b:%v\n", string(b))
}

学新通
// GET请求 ,把一些 参数 做成 变量 而不是 直接放到url
func TestGet2() {
	//设置一个map类型数据
	params := url.Values{}
	//将 string类型数据 解析为 URL 格式
	Url, err := url.Parse("http://apis.juhe.cn/simpleWeather/query")
	if err != nil {
		return
	}
	//设置 键值对
	params.Set("key", "b464cc38b226061e79adcf6b722b0e54")
	params.Set("city", "北京")
	//如果参数中有 中文参数,这个方法会进行 URL Encode
	//city=北京&key=b464cc38******722b0e54
	//Url.RawQuery的值为url中 ?后面的值
	Url.RawQuery = params.Encode()
	// Url.String() 将URL重新组合为有效的URL字符串
	urlPath := Url.String()
	resp, err := http.Get(urlPath)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	b, _ := ioutil.ReadAll(resp.Body)
	fmt.Printf("b:%v\n", string(b))
}

学新通

2.解析JSON类型返回的数据

//http://httpbin.org/ 测试请求网址
func TestParseJson() {
	type result struct {
		Args    string            `json:"args"`
		Headers map[string]string `json:"headers"`
		Origin  string            `json:"origin"`
		Url     string            `json:"url"`
	}
	resp, err := http.Get("http://httpbin.org/get")
	if err != nil {
		return
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))
	var res result
	//将 body 解析到结构体类型的res变量
	json.Unmarshal(body, &res)
	fmt.Printf("%#v", res)
}
学新通

3.GET请求添加请求头

//添加头信息
func TestAddHeader() {
	//一个Client实例 就是一个HTTP客户端
	client := &http.Client{}
	//NewRequest使用指定的方法、网址和可选的主题创建并返回一个新的 *Request。
	req, _ := http.NewRequest("GET", "http://httpbin.org/get", nil)
	// 添加 头信息
	req.Header.Add("name", "OCEAN")
	req.Header.Add("age", "80")
	//执行发送HTTP请求并返回HTTP响应,
	resp, _ := client.Do(req)
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))

}

学新通

4.发起POST请求

//发出post请求
func TestPost() {
	urlstr := "http://apis.juhe.cn/simpleWeather/query"
	values := url.Values{}
	values.Set("key", "b464cc38b226061e79adcf6b722b0e54")
	values.Set("city", "上海")
	//PostForm向指定的URL发送一个POST,数据的键和值被URL编码为请求体。
	res, err := http.PostForm(urlstr, values)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()
	b, _ := ioutil.ReadAll(res.Body)
	fmt.Println(string(b))
}
//发出post请求
func TestPost2() {
	urlValue := url.Values{
		"name": {"OCEAN"},
		"age":  {"80"},
	}
	reqBody := urlValue.Encode()
	//"text/html"为POST数据的类型
	//strings.NewReader(reqBody)为POST数据,作为请求的主体。
	//strings.NewReader创建一个从s读取数据的Reader
	resp, _ := http.Post("http://httpbin.org/post", "text/html", strings.NewReader(reqBody))
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))
}

5.发送JSON数据的post请求

// 发送JSON数据的 post请求
func TestPost3() {
	//一个Client实例 就是一个HTTP客户端
	client := &http.Client{}
	data := make(map[string]interface{})
	data["name"] = "ocean赵"
	data["age"] = "23"
	//Marshal函数返回data的json编码
	bytesData, _ := json.Marshal(data)
	req, _ := http.NewRequest("POST", "http://httpbin.org/post", bytes.NewReader(bytesData))
	//发送 HTTP请求 并返回 HTTP 响应
	resp, _ := client.Do(req)
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))
}

5.1不用client的post请求

func TEST(){
  	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))
}

6. 使用Client自定义请求

//使用Client自定义请求
func TestClient() {
	url := "http://apis.juhe.cn/simpleWeather/query?city=北京&key=b464cc38b226061e79adcf6b722b0e54"
	client := http.Client{
		Timeout: time.Second * 5,
	}
	req, _ := http.NewRequest(http.MethodGet, url, nil)
	res, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)
	fmt.Println(string(body))
}

7.实现 HTTP Server

在这里func MyServer() {
	//resp,给客户端回复数据  响应
	//req  读取客户端发送的数据  请求
	f := func(resp http.ResponseWriter, req *http.Request) {
		//WriteString函数将字符串"helloworld!!"的内容写入resp中
		io.WriteString(resp, "helloworld!!")
	}
	//注册一个处理器函数 ,调用给定模式的处理函数 f
	http.HandleFunc("/hello", f)
	//使用指定的监听地址和处理器启动一个HTTP服务端
	//ListenAndServe监听TCP网络地址 ":9999"
	http.ListenAndServe(":9999", nil)
}

访问 :http://localhost:9999/hello 显示 helloworld!!

8. 使用Handler实现并发处理

//使用Handler实现并发处理
type countHandler struct {
	//Mutex 是最简单的一种锁类型,同时也比较暴力,当一个 goroutine 获得了 Mutex 后,
	//其他 goroutine 就只能乖乖等到这个 goroutine 释放该 Mutex
	mu sync.Mutex //guards n
	n  int
}
func (h *countHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	h.mu.Lock()         //上锁
	defer h.mu.Unlock() //解锁
	h.n  
	//Fprintf根据格式说明符进行格式化,并写入w
	fmt.Fprintf(w, "count is %d\n", h.n)
}
func testHttpServer2() {
	//Handle注册HTTP处理器handler和对应的模式"/count"
	http.Handle("/count", new(countHandler))
	log.Fatal(http.ListenAndServe(":8080", nil))
}
学新通

每次访问 http://localhost:8080/count 值都会增加

9.

10.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgeigfi
系列文章
更多 icon
同类精品
更多 icon
继续加载