zoukankan      html  css  js  c++  java
  • Go语言中的HTTP

    Go中的http使用

    package main
    
    import (
    	"fmt"
    	"net/http"
    	"io/ioutil"
    	"strings"
    	"net/url"
    )
    
    func httpGet(){
    	resp, err := http.Get("http://www.baidu.com")
    	if err != nil {
    		fmt.Println(err)
    		return
    	}
    	defer resp.Body.Close()
    	body, err := ioutil.ReadAll(resp.Body)
    	if err != nil {
    		fmt.Println(err)
    		return
    	}
    	fmt.Println(string(body))
    }
    
    func httpPost(){
    	resp, err := http.Post("http://www.baidu.com",
    "application/x-www-form-urlencoded",
    strings.NewReader("name=zzr"))
    if err != nil {
    	fmt.Println(err)
    	return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
    	fmt.Println(err)
    	return
    }
    fmt.Println(string(body))
    }
    
    func httpPostForm(){
    	resp, err := http.PostForm("http://www.baidu.com",
    	url.Values{"key":{"value"}, "id":{"123"}})
    
    	if err != nil {
    		fmt.Println(err)
    		return
    	}
    	defer resp.Body.Close()
    	body, err := ioutil.ReadAll(resp.Body)
    	if err != nil {
    		fmt.Println(err)
    		return
    	}
    	fmt.Println(string(body))
    }
    
    func httpDo(){
    	client := &http.Client{}
    
    	req, err := http.NewRequest("POST", "http://www.baidu.com",strings.NewReader("name=zzr"))
    	if err != nil{
    		fmt.Println(err)
    		return
    	}
    	req.Header.Set("Content-Type", "application/x-www.form-urlencoded")
    	req.Header.Set("Cookie", "name=ben")
    
    	resp, err := client.Do(req)
    
    	defer resp.Body.Close()
    
    	body, err := ioutil.ReadAll(resp.Body)
    	if err != nil {
    		fmt.Println(err)
    		return
    	}
    	fmt.Println(string(body))
    }
    func main(){
    	httpPost()	
    }
    
  • 相关阅读:
    建立适当的索引
    Windows 10Bash命令
    代码生成工具介绍和使用
    分布式的任务调度框架
    Net分布式系统
    Keepalived+LVS+Nginx负载均衡之高可用
    call,apply,bind
    2015搜狐在线笔试题(内存泄露问题)(转)
    十步完全理解SQL(转)
    Linux shell用法和技巧(转)
  • 原文地址:https://www.cnblogs.com/zzr-stdio/p/9671647.html
Copyright © 2011-2022 走看看