微慑信息网

[ GO ]Go语言进行http POST请求の两种方式

1、

package main

import (
	"fmt"
	"net/http"
	"net/url"
	"strings"
)

func main() {
	url := "https://httpbin.org/post"
	data := url.Values{}
	data.Set("username", "user")
	data.Set("password", "pass")
	payload := strings.NewReader(data.Encode())

	req, err := http.NewRequest("POST", url, payload)
	if err != nil {
		fmt.Println(err)
		return
	}
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()

	fmt.Println("response Status:", resp.Status)
	fmt.Println("response Headers:", resp.Header)
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("response Body:", string(body))
}

 

2、

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    url := "http://example.com/path/to/api"
    data := []byte("action=wpcom_load_posts&page=2&type=default&exclude=")
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(body))
}

 

本文标题:[ GO ]Go语言进行http POST请求の两种方式
本文链接:
(转载请附上本文链接)
https://vulsee.com/archives/vulsee_2023/0525_16919.html
转载请附本站链接,未经允许不得转载,,谢谢:微慑信息网-VulSee.com » [ GO ]Go语言进行http POST请求の两种方式
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

微慑信息网 专注工匠精神

访问我们联系我们