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))
}}