zoukankan      html  css  js  c++  java
  • 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
    */
    
    
  • 相关阅读:
    Java String字符串深入详解
    每日linux命令学习-sed
    每日linux命令学习-历史指令查询(history、fc、alias)
    每日linux命令学习-rpm命令
    每日linux命令学习-head命令和tail命令
    每日linux命令学习-lsattr和chattr
    每日linux命令学习-xargs命令
    每日linux命令学习-read命令
    测试mysql性能工具
    mysql 免安装版文件含义及作用
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8635835.html
Copyright © 2011-2022 走看看