当前位置: 代码网 > it编程>前端脚本>Golang > golang如何用http.NewRequest创建get和post请求

golang如何用http.NewRequest创建get和post请求

2024年05月15日 Golang 我要评论
golang用http.newrequest创建get和post请求在go语言中,使用http.newrequest函数可以创建get和post请求。下面是一个示例代码,演示如何使用http.newr

golang用http.newrequest创建get和post请求

在go语言中,使用http.newrequest函数可以创建get和post请求。

下面是一个示例代码,演示如何使用http.newrequest创建get和post请求:

package main

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

func main() {
 // 创建get请求
 getrequest, err := http.newrequest("get", "https://api.example.com/data", nil)
 if err != nil {
 fmt.println("创建get请求失败:", err)
 return
 }

 // 发送get请求并获取响应
 client := &http.client{}
 getresponse, err := client.do(getrequest)
 if err != nil {
 fmt.println("发送get请求失败:", err)
 return
 }
 defer getresponse.body.close()

 // 读取get响应的内容
 getresponsebody, err := ioutil.readall(getresponse.body)
 if err != nil {
 fmt.println("读取get响应失败:", err)
 return
 }

 // 打印get响应的内容
 fmt.println(string(getresponsebody))

 // 创建post请求
 postdata := []byte(`{"key1": "value1", "key2": "value2"}`)
 postrequest, err := http.newrequest("post", "https://api.example.com/data", bytes.newbuffer(postdata))
 if err != nil {
 fmt.println("创建post请求失败:", err)
 return
 }
 postrequest.header.set("content-type", "application/json") // 设置请求头,指定内容类型为json

 // 发送post请求并获取响应
 postresponse, err := client.do(postrequest)
 if err != nil {
 fmt.println("发送post请求失败:", err)
 return
 }
 defer postresponse.body.close()

 // 读取post响应的内容
 postresponsebody, err := ioutil.readall(postresponse.body)
 if err != nil {
 fmt.println("读取post响应失败:", err)
 return
 }

 // 打印post响应的内容
 fmt.println(string(postresponsebody))
}

在上述示例中,我们首先创建了一个get请求,指定了请求的url为"https://api.example.com/data"。

然后,我们使用http.client类型的客户端发送该请求,并获取响应。

对于post请求,我们创建了一个包含json数据的请求主体,并设置了请求头的"content-type"字段为"application/json"。

然后,我们使用相同的客户端发送该请求,并获取响应。

最后,我们读取并打印了get和post响应的内容。

go post 调用http.newrequest出现错误:400 bad request踩坑

问题

使用go语言的http.newrequest函数调用接口,该函数可带有post参数

但是一直出现错误:400 bad request

看网上解决都是说输入格式等问题,但是查询json结构体等信息并无错误。

解决

问题出在这条语句:

req, err := http.newrequest("post", url, bytes.newbuffer(data))

第一个参数method真正的参数应该是post,都是大写。

这很坑,或者说很容易忽略这个问题,如果不小心写错的话,一般不会把问题考虑到这,而是疯狂去看json格式是否符合,那么问题就得很久才能解决了。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com