本文介绍: http请求封装项目中非常普遍,下面笔者封装http post请求jsonformget请求,以备将来使用

http请求封装项目中非常普遍,下面笔者封装http post请求jsonformget请求,以备将来使用

1、POST请求

1.1、POST请求发送 json

这里发送json笔者使用了2种方式,一种是golang 自带的 http.Post方法,另一是 http.NewRequest

方法二者区别http.Post方法不能发送自定义header数据;而http.NewRequest方法可以发送额外的自定义header数据

先看使用golang 自带的 http.Post方法封装的POST请求

func HttpPostJson(url string, requestBody []byte) (string, error) {
	response, er := http.Post(url, "application/json", bytes.NewBuffer(requestBody))
	if er != nil {
		return "", er
	}
	defer response.Body.Close()
	body, er2 := ioutil.ReadAll(response.Body)
	if er2 != nil {
		return "", er2
	}
	return string(body), nil
}

再看使用http.NewRequest方法封装的POST请求

golang源代码可以知道 http.Post方法底层就是使用的 NewRequest 方法,因此NewRequest方法更加灵活

func HttpPost(url string, header map[string]string, requestBody []byte) (string, error) {
	httpClient := &http.Client{}

	request, er := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(requestBody))
	if er != nil {
		return "", er
	}

	for key, value := range header {
		request.Header.Set(key, value)
	}
	//设置请求头Content-Type
	request.Header.Set("Content-Type", "application/json")
	response, er2 := httpClient.Do(request)
	if er2 != nil {
		return "", er2
	}
	defer response.Body.Close()
	body, er3 := ioutil.ReadAll(response.Body)
	if er3 != nil {
		return "", er3
	}
	return string(body), nil
}

1.2、POST请求发送form

form数据使用map存放map的key字符串value字符串切片

func HttpPostForm(url string, form map[string][]string) (string, error) {
	response, er := http.PostForm(url, form)
	if er != nil {
		return "", er
	}
	defer response.Body.Close()
	body, er2 := ioutil.ReadAll(response.Body)
	if er2 != nil {
		return "", er2
	}
	return string(body), nil
}

可以携带自定义header的post请求发送form

笔者使用NewRequest 方法封装的可以携带自定义header的form请求

func HttpPostHeaderForm(requestUrl string, header map[string]string, form map[string][]string) (string, error) {
	httpClient := &http.Client{}
	var data url.Values
	data = map[string][]string{}
	for k, v := range form {
		data[k] = v
	}
	request, er := http.NewRequest(http.MethodPost, requestUrl, strings.NewReader(data.Encode()))
	if er != nil {
		return "", er
	}
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	//设置自定义header
	for key, value := range header {
		request.Header.Set(key, value)
	}

	response, er := httpClient.Do(request)
	if er != nil {
		return "", er
	}
	defer response.Body.Close()
	body, er2 := ioutil.ReadAll(response.Body)
	if er2 != nil {
		return "", er2
	}
	return string(body), nil
}

2、GET请求

func HttpGet(url string) (string, error) {
	response, er := http.Get(url)
	if er != nil {
		return "", er
	}
	defer response.Body.Close()
	body, er2 := ioutil.ReadAll(response.Body)
	if er2 != nil {
		return "", er2
	}
	return string(body), nil
}

3、测试

这里服务端笔者使用springboot项目创建用来接收请求,端口默认8080

参数

package com.wsjz.demo.param;

import lombok.Data;


@Data
public class AddParam {

    private String name;

    private Integer age;
}

controller

package com.wsjz.demo.controller;

import com.wsjz.demo.param.AddParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;

@RestController
public class DemoController {

    @PostMapping("/json/add")
    public String jsonAdd(@RequestBody AddParam param, HttpServletRequest request) {
        System.out.println(request.getHeader("token"));
        System.out.println(param);
        return "json ok";
    }

    @PostMapping("/form/add")
    public String formAdd(AddParam param, HttpServletRequest request) {
        System.out.println(request.getHeader("token"));
        System.out.println(param);
        return "form ok";
    }

    @GetMapping("/get/add")
    public String getAdd(AddParam param) {
        System.out.println(param);
        return "get ok";
    }

}

golang测试代码

新建User结构体做为参数

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

(1)、测试HttpPostJson方法

func TestHttpPostJson(t *testing.T) {
	url := "http://localhost:8080/json/add"

	var user = User{
		Name: "举头西北浮云,倚天万里须长剑,人言此地,夜深长见,斗牛光焰",
		Age:  17,
	}
	requestBody, er := json.Marshal(user)
	if er != nil {
		log.Fatal(er)
	}
	response, er := HttpPostJson(url, requestBody)
	if er != nil {
		fmt.Println(er)
	}
	fmt.Println(response)
}

运行效果

(2)、测试HttpPost方法

func TestHttpPost(t *testing.T) {
	url := "http://localhost:8080/json/add"
	var header = make(map[string]string)
	header["token"] = "2492dc007dfc4ce8adcc8b42b21641f4"

	var user = User{
		Name: "我见青山多妩媚",
		Age:  17,
	}
	requestBody, er := json.Marshal(user)
	if er != nil {
		log.Fatal(er)
	}
	response, er2 := HttpPost(url, header, requestBody)
	if er2 != nil {
		log.Fatal(er2)
	}
	fmt.Println(response)
}

运行效果

(3)、测试HttpPostForm方法

func TestHttpPostForm(t *testing.T) {
	url := "http://localhost:8080/form/add"
	var form = make(map[string][]string)
	form["name"] = []string{"可怜今夕月,向何处,去悠悠"}
	form["age"] = []string{"18"}
	response, er := HttpPostForm(url, form)
	if er != nil {
		fmt.Println(er)
	}
	fmt.Println(response)
}

运行效果

(4)、测试HttpPostHeaderForm方法

func TestHttpPostHeaderForm(t *testing.T) {
	url := "http://localhost:8080/form/add"
	var header = make(map[string]string)
	header["token"] = "0a8b903b7d7448e3ab007caab081965c"
	var form = make(map[string][]string)
	form["name"] = []string{"相思字,空盈幅,相思意,何时足"}
	form["age"] = []string{"18"}

	response, er := HttpPostHeaderForm(url, header, form)
	if er != nil {
		fmt.Println(er)
	}
	fmt.Println(response)
}

运行效果

(5)、测试HttpGet方法

func TestHttpGet(t *testing.T) {
	//对中文进行编码
	name := url.QueryEscape("乘风好去,长空万里,直下看山河")
	requestUrl := "http://localhost:8080/get/add?name=" + name + "&age=19"
	response, er := HttpGet(requestUrl)
	if er != nil {
		fmt.Println(er)
	}
	fmt.Println(response)
}

运行效果

至此完

原文地址:https://blog.csdn.net/wsjzzcbq/article/details/130979214

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_11073.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注