Skip to content

Latest commit

 

History

History
366 lines (314 loc) · 6.52 KB

7.3.md

File metadata and controls

366 lines (314 loc) · 6.52 KB

7.3 http客户端(GET、POST、POSTFORM、DO)

示例:

1、实现Get请求方法

package main

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

func main() {
   requestUrl := "http://www.baidu.com"
   response, err := http.Get(requestUrl)

   if err != nil {
      fmt.Println(err)
   }

   defer response.Body.Close()

   body, _ := ioutil.ReadAll(response.Body)
   fmt.Println(string(body))
}

2、实现post请求方法

package main

import (
   "bytes"
   "fmt"
   "io/ioutil"
   "net/http"
   "net/url"
)

func main() {
   requestUrl := "http://www.baidu.com/"
   postValue := url.Values{
      "username": {"aa"},
      "address":  {"bb"},
      "subject":  {"cc"},
      "form":     {"dd"},
   }
   //request, err := http.PostForm(requestUrl, postValue)

   body := bytes.NewBufferString(postValue.Encode())
   request, err := http.Post(requestUrl, "text/html", body)
   if err != nil {
      fmt.Println(err)
   }

   defer request.Body.Close()
   fmt.Println(request.StatusCode)
   if request.StatusCode == 200 {
      rb, err := ioutil.ReadAll(request.Body)
      if err != nil {
         fmt.Println(rb)
      }
      fmt.Println(string(rb))
   }
}

3、 实现PostForm请求方法

package main

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

func main() {
   requestUrl := "http://www.baidu.com/"
   postValue := url.Values{
      "username": {"aa"},
      "address":  {"bb"},
      "subject":  {"cc"},
      "form":     {"dd"},
   }
   request, err := http.PostForm(requestUrl, postValue)
   if err != nil {
      fmt.Println(err)
   }

   defer request.Body.Close()
   fmt.Println(request.StatusCode)
   if request.StatusCode == 200 {
      rb, err := ioutil.ReadAll(request.Body)
      if err != nil {
         fmt.Println(rb)
      }
      fmt.Println(string(rb))
   }
}

4、http.Do

使用http.Do方法可以在请求的时候设置头参数、cookie之类的数据。

package main

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

func main() {
   client := &http.Client{}

   request, err := http.NewRequest("GET", "http://www.baidu.com", nil)
   if err != nil {
      fmt.Println(err)
   }

   cookie := &http.Cookie{Name: "JERRY", Value: "dkfsf"}
   request.AddCookie(cookie) //向request中添加cookie

   //设置request的header
   request.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")

   response, err := client.Do(request)
   if err != nil {
      fmt.Println(err)
      return
   }

   defer response.Body.Close()
   fmt.Println(response.StatusCode)
   if response.StatusCode == 200 {
      r, err := ioutil.ReadAll(response.Body)
      if err != nil {
         fmt.Println(err)
      }
      fmt.Println(string(r))
   }
}

5、json清求

package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

type Student struct {
	Name string
}
func main()  {
	requestUrl:="http://127.0.0.1:8090/"
	stu := Student{
		Name:"lamber",
	}
	s,_ := json.Marshal(&stu)
	HttPJson("GET",requestUrl,s)
}

func HttPJson(method string, url string, postValue[]byte) ([]byte, error) {
	body:=bytes.NewBuffer([]byte(postValue))
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	if res.StatusCode == http.StatusOK {
		return nil, errors.New(fmt.Sprintf("response status code %v", res.StatusCode))
	}

	rb, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	return rb, nil
}

6、 PUT请求

package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
)

type Student struct {
	Name string
}
func main()  {
	requestUrl:="http://127.0.0.1:8090/"
	stu := Student{
		Name:"lamber",
	}
	s,_ := json.Marshal(&stu)
	HttpPut(requestUrl,s)
}

func HttpPut( url string, params []byte) ([]byte, error) {
	body := bytes.NewBuffer(params)
	req, err := http.NewRequest("PUT", url, body)
	if err != nil {
		return nil, err
	}
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	if res.StatusCode == http.StatusOK {
		return nil, errors.New(fmt.Sprintf("response status code %v", res.StatusCode))
	}

	rb, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	return rb, nil
}

7、 delete请求

package main

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

type Student struct {
	Name string
}
func main()  {
	requestUrl:="http://127.0.0.1:8090/"
	HttpDelete(requestUrl)
}

func HttpDelete( url string) ([]byte, error) {
	req, err := http.NewRequest("DELETE", url, nil)
	if err != nil {
		return nil, err
	}
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	if res.StatusCode == http.StatusOK {
		return nil, errors.New(fmt.Sprintf("response status code %v", res.StatusCode))
	}
	rb, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	return rb, nil
}

8、上传文件

package main

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
)

type Student struct {
	Name string
}
func main()  {
	requestUrl:="http://127.0.0.1:8090/upload"

	path, _ := os.Getwd()
	path += "/test.txt"
	extraParams := map[string]string{
		"name":       "hi",
	}
	//extraParams 提交别的参数
	res,err:=HttpPostFiles(requestUrl,extraParams,"file",path)
	fmt.Println(res,err)
}

func HttpPostFiles(uri string, params map[string]string, paramName, path string) ([]byte, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	// 实例化multipart
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	// 创建multipart 文件字段,注意paramName要跟服务端一致
	part, err := writer.CreateFormFile(paramName, path)
	if err != nil {
		return nil, err
	}
	_, err = io.Copy(part, file)

	for key, val := range params {
		_ = writer.WriteField(key, val)
	}
	err = writer.Close()
	if err != nil {
		return nil, err
	}
	request, err := http.NewRequest("POST", uri, body)
	request.Header.Set("Content-Type", writer.FormDataContentType())
	res, err := http.DefaultClient.Do(request)
	if res.StatusCode != http.StatusOK {
		return nil, errors.New(fmt.Sprintf("response status code %v", res.StatusCode))
	}
	rb, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	return rb, nil
}

links