go语言模拟post请求----go语言学习笔记(一)

go模拟json格式数据请求方式:

package main

import (
"net/http"
"fmt"
"io/ioutil"
"bytes")
  func main(){
  url := "http://www.baidu.com/" //你要请求的url地址
  cx_json :={"user":"aaa","usernam":"aaaaaa"} //传递的json格式的参数,有时需要格式化
var jsonStr = []byte(cx_json)
  req,err :=http.NewRequest("POST",url,bytes.NewBuffer(jsonStr))

  req.Header.Set("Content-Type", "application/json")
    client :=&http.Client{}
    resp,err :=client.Do(req)

    if err !=nil{
        panic(err)
    }

    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("response Body:", string(body))
}

go 模拟form表单的post请求:

import (
    "fmt"
    "net/http"
    "net/url"
    "io/ioutil"
    "encoding/json"
    "time"
)


func main(){
    postValue := url.Values{
        "username": {"aaaa"},
        "user":{"aaaa"},
    }
    resp,err :=http.PostForm("http://www.baidu.com",postValue)
    resp.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    if err != nil{
        fmt.Println(err)
    }
    defer resp.Body.Close()
    body,err := ioutil.ReadAll(resp.Body)
    if err != nil{
panic(err)}
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("response Body:", string(body))
 }}
原文地址:https://www.cnblogs.com/jinjidedale/p/8257252.html