• 7.4 http request post get


    
    package main
    
    import (
    	"fmt"
    	"io/ioutil"
    	"net/http"
    	"net/url"
    	"strings"
    )
    
    type StringServer string
    
    func (s StringServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
    	req.ParseForm()
    	fmt.Printf("Received form data: %v
    ", req.Form)
    	rw.Write([]byte(string(s)))
    }
    
    func createServer(addr string) http.Server {
    	return http.Server{
    		Addr:    addr,
    		Handler: StringServer("Hello world"),
    	}
    }
    
    const addr = "localhost:7070"
    
    func main() {
    	s := createServer(addr)
    	go s.ListenAndServe()
    
    	useRequest()
    	simplePost()
    
    }
    
    func simplePost() {
    	res, err := http.Post("http://localhost:7070",
    		"application/x-www-form-urlencoded",
    		strings.NewReader("name=Radek&surname=Sohlich"))
    	if err != nil {
    		panic(err)
    	}
    
    	data, err := ioutil.ReadAll(res.Body)
    	if err != nil {
    		panic(err)
    	}
    	res.Body.Close()
    	fmt.Println("Response from server:" + string(data))
    }
    
    func useRequest() {
    
    	hc := http.Client{}
    	form := url.Values{}
    	form.Add("name", "Radek")
    	form.Add("surname", "Sohlich")
    
    	req, err := http.NewRequest("POST",
    		"http://localhost:7070",
    		strings.NewReader(form.Encode()))
    	req.Header.Add("Content-Type",
    		"application/x-www-form-urlencoded")
    
    	res, err := hc.Do(req)
    
    	if err != nil {
    		panic(err)
    	}
    
    	data, err := ioutil.ReadAll(res.Body)
    	if err != nil {
    		panic(err)
    	}
    	res.Body.Close()
    	fmt.Println("Response from server:" + string(data))
    }
    
    /*
    Received form data: map[name:[Radek] surname:[Sohlich]]
    Response from server:Hello world
    Received form data: map[surname:[Sohlich] name:[Radek]]
    Response from server:Hello world
    */
    
    
  • 相关阅读:
    sqlserver 把两个sql查询语句查询出来的两张表合并成一张表
    highcharts series几种写法
    Collection、 List 、Set接口 LinkedList 、HashSet类, Collections 集合工具类
    java.io.File
    Object、Objects
    java.lang.StringBuilder
    String
    java学习日记(17-18)
    java学习日记(14-16)
    java学习日记(8-13)
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8635835.html
Copyright © 2020-2023  润新知