首页 > 学院 > 开发设计 > 正文

Golang http Get 和 Post

2019-11-11 04:24:07
字体:
来源:转载
供稿:网友
// 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))    }}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表