最近开始尝试使用 golang 写一个小工具,在登陆网站的时候做了个 post 请求,但是返回的页面还是登陆页面,同样的参数用 postman 做 post ,得到的响应是登录成功后的页面,请问 postman 还做了什么处理吗?或者我这里还需要怎么操作
代码如下:
var reqBody = "username=" + number + "&password=" + url.QueryEscape(passwd)
client := &http.Client{}
req, err := http.NewRequest("POST", "https://****", strings.NewReader(reqBody))
if err != nil {
logSomething.LogError("failed to make a new request, err:%s", err)
return nil, 0, err
}
req.Header.Set("Host", "****")
req.Header.Set("Content-Length", strconv.Itoa(len(reqBody)))
req.Header.Set("Cache-Control", "max-age=0")
req.Header.Set("Sec-Ch-Ua", "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"96\", \"Google Chrome\";v=\"96\"")
req.Header.Set("Sec-Ch-Ua-Mobile", "?0")
req.Header.Set("Sec-Ch-Ua-Platform", "\"Windows\"")
req.Header.Set("Origin", "https://*****")
req.Header.Set("Upgrade-Insecure-Requests", "1")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36")
req.Header.Set("Accept", "text/html")
req.Header.Set("Sec-Fetch-Site", "same-origin")
req.Header.Set("Sec-Fetch-Mode", "navigate")
req.Header.Set("Sec-Fetch-User", "?1")
req.Header.Set("Sec-Fetch-Dest", "document")
req.Header.Set("Referer", "https://*****")
req.Header.Set("Accept-Encoding", "gzip")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
req.Header.Set("Connection", "close")
resp, err := client.Do(req)
if err != nil {
logSomething.LogError("failed to sent a new request, err:%s", err)
return nil, 0, err
}
defer resp.Body.Close()
1
pmx1990 2022-01-18 16:07:22 +08:00
postman 点一下 code 复制下 curl 内容 对比下 就完事了啊
|
2
zszhere 2022-01-18 16:27:29 +08:00 via iPhone
postman 是跟随了 302 跳转到登陆成功页面了吧
|
3
hingle 2022-01-18 16:55:15 +08:00
用 cookiejar 试一下,登录后服务端应该会返回 Set-Cookie ,有 cookie 才能显示登录成功后的页面。
|
4
hingle 2022-01-18 16:57:04 +08:00
还有 Accept-Encoding: gzip 可能会让 resp.body 显示乱码。
|
5
TOUJOURSER 2022-01-18 17:21:55 +08:00
golang 如果要设定 Host 需要通过 req.Host="xxxx" 而不是 req.Header.Set("Host", "****")
|
6
deavorwei OP @zszhere 感谢提醒,goalng 会自动跟随重定向,但是不会带上 cookie ,我设置了下 cookiejar 就 ok 了
|
7
deavorwei OP @hingle 感谢,我 new 了一个 jar 搞定了,client := &http.Client{Jar: jar}。gzip 我有在 golang 解码,感谢提醒
|
8
deavorwei OP @TOUJOURSER 噢,了解了,这就改,感谢感谢
|