Go语言入门经典第19章

1.打印状态码

package main

import (
	"fmt"
	"net/http"
)
func main() {
	url := "https://www.baidu.com/404"
	response, err := http.Get(url)
	if err != nil {
		fmt.Println("http get error",err)
		return 
	}
	defer response.Body.Close()
	fmt.Println(response.Status)
	fmt.Println(response.StatusCode) //404
	fmt.Println(response.Proto)
}

2.发送post请求

package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
	"strings"
)


func main() {
	httpPost()
	//httpPostForm()
}

func httpPost() {
    resp, err := http.Post("http://www.01happy.com/demo/accept.php",
        "application/x-www-form-urlencoded",
        strings.NewReader("name=cjb123s"))
    if err != nil {
        fmt.Println(err)
    }
 
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }
	fmt.Println(resp.Status)
    fmt.Println(string(body))
}

/*
func httpPostForm() {

    resp, err := http.PostForm("http://www.01happy.com/demo/accept.php",
	    url.Values{"key": {"Value"}, "id": {"123"}})
 
    if err != nil {
        // handle error
    }
 
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }
 
    fmt.Println(string(body))
 
}
*/

3.添加自定义header发送get请求

package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
)
func main() {
	url := "https://www.baidu.com"
	httpDo(url)
}

func httpDo(url string) {
    client := &http.Client{}
 
    req, err := http.NewRequest("GET", "http://www.jd.com", nil)
    if err != nil {
        // handle error
	}
	//2种
	req.Header.Add("user-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3314.0 Safari/537.36 SE 2.X MetaSr 1.0")
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    req.Header.Set("Cookie", "name=anny")
 
    resp, err := client.Do(req)
	fmt.Println(resp.Status)
	
    defer resp.Body.Close()
 
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }
	err = ioutil.WriteFile("jd.html", body, 0666)
	if err != nil {
		fmt.Println("ioutil.WriteFile error", err)
		return 
	}else {
		fmt.Println(url, " ok")
		//count <- 1
	}
    //fmt.Println(string(body))
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值