Golang Http 學習

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章