模拟浏览器发起请求

实现get方法

  1. package main
  2. func main(){
  3. // 模拟浏览器
  4. response,err:=http.Get("http://localhost:8888/help")
  5. // 只有这三个方法
  6. //
  7. if err !=nil{
  8. fmt.Println(err)
  9. }
  10. fmt.Println(response.Proto)
  11. fmt.Println(response.StatusCode)
  12. io.Copy(os.Stdout,response.Body)
  13. }

NewRequest函数

包中只有 http.Post、http.Head、http.Get 三个方法,但这三个方法都是NewRequest函数的封装,其他方法可以通过http.NewRequest函数来执行

  1. req,err:=http.NewRequest("DELETE","http://localhost:8888/home",nil) //DELETE位方法名,会返回一个request的指针类型
  2. //发起请求要有一个client端,在http包中是一个结构体,如下
  3. client:=http.Client{}
  4. response,err=client.Do(req)
  5. io.Copy(os.Stdout,response.Body)
  6. //https协议的:
  7. response,err:=http.Get("https://www.baidu.com")
  8. io.Copy(os.Stdout,response.Body)

在访问不受信的https网站时,需要使用原生的request,而不能使用封装好的Get、Post、Head方法

  1. req,err:=http.NewRequest("GET","http://localhost:8888/home",nil)
  2. client:=http.Client{
  3. Transport: &http.Transport{
  4. TLSClientConfig: &tls.Config{
  5. InsecureSkipVerify: true,
  6. },
  7. },
  8. }
  9. response,err:=client.Do(req)
文档更新时间: 2021-08-22 18:24   作者:张尚