zoukankan      html  css  js  c++  java
  • 7.6 request form post

    
    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)
    	fmt.Printf("Received header: %v
    ", req.Header)
    	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()
    
    	form := url.Values{}
    	form.Set("id", "5")
    	form.Set("name", "Wolfgang")
    
    	req, err := http.NewRequest(http.MethodPost,
    		"http://localhost:7070",
    		strings.NewReader(form.Encode()))
    
    	if err != nil {
    		panic(err)
    	}
    	req.Header.Set("Content-Type",
    		"application/x-www-form-urlencoded")
    
    	res, err := http.DefaultClient.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[id:[5] name:[Wolfgang]]
    Received header: map[User-Agent:[Go-http-client/1.1] Content-Length:[18] Content-Type:[application/x-www-form-urlencoded] Accept-Encoding:[gzip]]
    Response from server:Hello world
    
    */
    
    
  • 相关阅读:
    JDK所有版本
    application.yml配置log日志
    eclipse配置lombok
    Eclipse配置springboot
    java 连接mongodb
    MongoDB shell操作
    mysql插入一万条数据
    Web设计精髓(转)
    SyntaxHighlighter -- 代码高亮插件
    input之placeholder与行高的问题。
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8635857.html
Copyright © 2011-2022 走看看