美文网首页
golang发送Form-data格式请求

golang发送Form-data格式请求

作者: DifferentMan | 来源:发表于2020-03-11 18:09 被阅读0次

在网上没找到合适的代码,发现有multipart库可以直接使用,代码如下:

package main

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

func main() {
    postData := make(map[string]string)
    postData["anchorId"] = "361155076095561728"
    postData["searchBegin"] = "2019-03-01 00:00:00"
    postData["searchEnd"] = "2020-03-10 00:00:00"
    url := "https:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    PostWithFormData("POST",url ,&postData)
}


func PostWithFormData(method, url string, postData *map[string]string){
    body := new(bytes.Buffer)
    w := multipart.NewWriter(body)
    for k,v :=  range *postData{
        w.WriteField(k, v)
    }
    w.Close()
    req, _ := http.NewRequest(method, url, body)
    req.Header.Set("Content-Type", w.FormDataContentType())
    resp, _ := http.DefaultClient.Do(req)
    data, _ := ioutil.ReadAll(resp.Body)
    resp.Body.Close()
    fmt.Println(resp.StatusCode)
    fmt.Printf("%s", data)
}

相关文章

网友评论

      本文标题:golang发送Form-data格式请求

      本文链接:https://www.haomeiwen.com/subject/rnjhjhtx.html