golang get/post 请求样例

package main

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

type LoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

func main() {
	//demo02()
	// samplePost()
	data := make(map[string]interface{})
	data["username"] = "zhangsan"
	data["password"] = "password"
	data["realname"] = "zhangqiang"
	data["email"] = "co.zjwblog@gmail.com"
	data["timestamp"] = time.Now().Format("2006-01-02 15:04:05.000")
	data["author"] = "zjw"
	//r, _ := PostWithJSON("http://www.baidu.com", data)
	//fmt.Println(r)
	r2, _ :=PostFormWithHttpPost2("http://www.baidu.com", data)
	fmt.Println(r2)
	data3 := url.Values{"start":{"0"}, "offset":{"xxxx"}}
	r3, _ := PostFormWithHttpPost1("http://www.baidu.com", data3)
	fmt.Println(r3)
}
  1. GET请求, 使用http.Get方法
func GetWithHttp(uri string) (string, error) {
	response, err := http.Get(uri)
	if err != nil {
		return "", err
	}
	b, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("err:", err)
		return "", err
	}
	return string(b), nil
}
  1. GET请求,使用http.Client{}
func GetWithClient(uri string) (string, error) {
	client := http.Client{}
	response, err := client.Get(uri)
	if err != nil {
		return "", err
	}
	b, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("err:", err)
		return "", err
	}
	return string(b), nil
}
  1. GET请求,basic方式
func GetWithBasic(uri string) (string, error) {
	request, err := http.NewRequest("GET", uri, nil)
	if err != nil {
		return "", err
	}
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		return "", err
	}
	b, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("err:", err)
		return "", err
	}
	return string(b), nil
}
  1. 发送POST请求(Form表单)示例1

func PostFormWithHttpPost1(uri string, data url.Values) (string, error) {
	response, err := http.Post(
		uri,
		"application/x-www-form-urlencoded",
		strings.NewReader(data.Encode()))
	if err != nil {
		return "", err
	}
	respBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("从Response中获取数据失败", err)
		return "", err
	}
	//byte数组直接转成string,优化内存
	result := *(*string)(unsafe.Pointer(&respBytes))
	return result, nil
}
  1. 发送POST请求(Form表单)示例2
func PostFormWithHttpPost2(uri string, data map[string]interface{}) (string, error) {
	var request http.Request
	request.ParseForm()
	for key, value := range data {
		request.Form.Add(key, value.(string))
	}
	body := strings.NewReader(request.Form.Encode())
	response, err := http.Post(uri, "application/x-www-form-urlencoded", body)
	if err != nil {
		return "", err
	}
	respBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("从Response中获取数据失败", err)
		return "", err
	}
	//byte数组直接转成string,优化内存
	result := *(*string)(unsafe.Pointer(&respBytes))
	return result, nil
}
  1. 使用client发送POST请求 示例1
func PostFormWithClientPost1(uri string, data url.Values) (string, error) {
	body := strings.NewReader(data.Encode())
	clt := http.Client{}
	resp, err := clt.Post(uri, "application/x-www-form-urlencoded", body)
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("从Response中获取数据失败", err)
		return "", err
	}
	//byte数组直接转成string,优化内存
	result := *(*string)(unsafe.Pointer(&respBytes))
	return result, nil
}
  1. 使用client发送POST请求 示例2
func PostFormWithClientPost2(uri string, data map[string]interface{}) (string, error) {
	var request http.Request
	request.ParseForm()
	for key, value := range data {
		request.Form.Add(key, value.(string))
	}
	body := strings.NewReader(request.Form.Encode())
	clt := http.Client{}
	resp, err := clt.Post("xxxx", "application/x-www-form-urlencoded", body)
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("从Response中获取数据失败", err)
		return "", err
	}
	//byte数组直接转成string,优化内存
	result := *(*string)(unsafe.Pointer(&respBytes))
	return result, nil
}
  1. 使用PostForm发送POST请求(Form表单)
func PostFormWithClientPostForm(uri string, data url.Values) (string, error) {
	var result string
	client := &http.Client{}

	response, err := client.PostForm(uri, data)
	if err != nil {
		fmt.Println("PostForm Err:", err)
		return result, err
	}
	respBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("从Response中获取数据失败", err)
		return result, err
	}
	//byte数组直接转成string,优化内存
	result = *(*string)(unsafe.Pointer(&respBytes))
	return result, nil
}
  1. 使用原始方式发POST请求
func PostFormWithBasic(uri string, data url.Values) (string, error) {
	body := strings.NewReader(data.Encode())
	req, err := http.NewRequest("POST", uri, body)
	if err != nil {
		return "", err
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	response, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	respBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("从Response中获取数据失败", err)
		return "", err
	}
	//byte数组直接转成string,优化内存
	result := *(*string)(unsafe.Pointer(&respBytes))
	return result, nil
}
  1. POST发送JSON数据请求(application/json)
func PostWithJSON(uri string, data map[string]interface{}) (string, error) {
	var result string
	b, err := json.Marshal(data)
	if err != nil {
		fmt.Println("解析Map数据失败:", err)
		return result, err
	}
	fmt.Println("URL:>", uri, "PostData:>", string(b))
	var reader = bytes.NewReader(b)
	request, err := http.NewRequest("POST", uri, reader)
	if err != nil {
		fmt.Println("创建用于请求的Request对象失败:", err)
		return result, err
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	client := http.Client{}
	response, err := client.Do(request)
	if err != nil {
		fmt.Println("发送Post请求失败:", err)
		return result, err
	}
	respBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("从Response中获取数据失败", err)
		return result, err
	}
	//byte数组直接转成string,优化内存
	result = *(*string)(unsafe.Pointer(&respBytes))
	return result, nil
}
  1. 其他示例
func demo02() {
	url := "http://www.baidu.com"

	username := "zhangsan"
	password := "password"
	loginRequest := LoginRequest{Username: username, Password: password}
	postData, err := json.Marshal(loginRequest)
	if err != nil {
		fmt.Println("Parse json failed:", err)
		return
	}
	fmt.Println("URL:>", url, "PostData:>", postData)
	fmt.Println("loginRequest:", bytes.NewBuffer(postData))
	reader := bytes.NewReader(postData)
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println("Http new Request object failed:", err)
		return
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")

	client := &http.Client{}

	response, err := client.Do(request)
	if err != nil {
		fmt.Println("Execute post request failed:", err)
		return
	}
	defer response.Body.Close()

	fmt.Println("response status:", response.Status)
	fmt.Println("response code:", response.StatusCode)
	fmt.Println("response headers:", response.Header)
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println("response body:", string(body))
}

func demo01() {
	response, err := http.Get("http://localhost:9000/http/user/?name=zhangsan")
	if err != nil {
		fmt.Println("err:", err)
		return
	}
	b, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("err:", err)
		return
	}
	fmt.Println(string(b))
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值