我想要调用http.NewRequest方法到服务器接口发送json数据,但是返回的结果是失败,但是用http.Post方法到服务器接口发送json数据成功,现在想不通问题出在什么地方,请给指点一二谢谢!
```
package hrlib
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
//人员用户考勤信息
type kqInfo struct {
UserLname string `json:"userLname"`
UserNo string `json:"userNo"`
Kssj string `json:"kssj"`
Jssj string `json:"jssj"`
}
type userInfo struct {
PageIndex int `json:"pageIndex"`
PageSize int `json:"pageSize"`
Search kqInfo `json:"search"`
}
//返回一个要查询的用户对象
func NewUserInfo() *userInfo {
var kssj = time.Date(2023, 6, 1, 8, 0, 0, 0, time.UTC).Format("2006-01-02 15:04:05")
var jssj = time.Date(2023, 6, 1, 23, 0, 0, 0, time.UTC).Format("2006-01-02 15:04:05")
return &userInfo{
PageIndex: 1,
PageSize: 3,
Search: kqInfo{
UserLname: "张三",
UserNo: "2016050395",
Kssj: kssj,
Jssj: jssj,
},
}
}
//获取用户考勤信息
func GetUser() {
var url = "http://192.168.1.100:20039/api/kq/getKqjl"
var kqUserInfo = NewUserInfo()
var kqData,err = json.Marshal(kqUserInfo)
if err != nil{
log.Println("json序列化错误")
return
}
req, err := http.NewRequest("post", url, bytes.NewReader(kqData))
if err != nil {
log.Println(err)
return
}
req.Header.Set("content-Type", "application/json")
var client = http.DefaultClient
resp, err := client.Do(req)
if err != nil {
log.Println("服务端响应失败")
return
}
//用Post这个方法返回的resp响应就没有问题
//resp,_:=http.Post(url,"application/json",bytes.NewReader(kqData))
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("数据读取失败")
return
}
fmt.Printf("%s\n", body)
}```
更多评论
> HTTP methods are **case-sensitive**, which means they should only be used in capital letters. Moreover, this is in contrast to HTTP header field names, which are case-insensitive.
#2