Golang http Get 和 Post

来源:互联网 发布:mac图库照片如何导出 编辑:程序博客网 时间:2024/05/03 20:37
// testHttpGetPost project main.gopackage mainimport (    "fmt"    "io/ioutil"    "net/http"    "strings"    . "github.com/soekchl/myUtils")const (    source_url = "https://www.baidu.com")func main() {    httpGet()    HttpPost()}func httpGet() {    response, err := http.Get(source_url)    if err != nil {        Error(err)        return    }    if response.Body != nil {        defer response.Body.Close()    }    body, err := ioutil.ReadAll(response.Body)    if response.StatusCode != 200 {        Error("网站获取错误!")        return    }    Notice("获取内容为:", string(body))}func HttpPost() {    data_str := fmt.Sprintf("name=%s&id=%v", "Luke", 1)    resp, err := http.Post(source_url, "application/x-www-form-urlencoded",        strings.NewReader(data_str))    if err != nil {        Error(err)        return    }    defer resp.Body.Close()    body, err := ioutil.ReadAll(resp.Body)    if err != nil {        Error(err)        return    }    if strings.Contains(string(body), "Successful") { // 这是按照post方法的 自定义返回值判断        Notice("数据发送成功!")    } else {        Error("数据发送失败!!!", string(body))    }}


                                             
0 0
原创粉丝点击