Go 发送 http 请求, PHP 获取不到参数

2019-07-03 16:49:57 +08:00
 noahsophie

#GO 客户端

client := &http.Client{}
req, err := http.NewRequest(
	"POST",
	"http://127.0.0.1/login/check",
	nil,
)
if err != nil {
	fmt.Println(err)
	return
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")

req.Body = ioutil.NopCloser(strings.NewReader("username=admin&password=123456"))
resp, _ := client.Do(req)
defer resp.Body.Close()

#PHP 服务端

file_get_contents("php://input") // 这里获取不到任何东西

#GO 服务端

func main() {
	http.HandleFunc("/test", testHtpp)
	http.ListenAndServe(":8085", nil)
}

func testHtpp(w http.ResponseWriter, r *http.Request) {
	body, _ := ioutil.ReadAll(r.Body)
	fmt.Println(string(body))  // 可以获取到 Body 的内容
}

请问为什么 php 获取不到任何内容

3311 次点击
所在节点    Go 编程语言
11 条回复
ben1024
2019-07-03 17:04:44 +08:00
试试
```php
var_dump($_POST)
```
lff0305
2019-07-03 17:12:18 +08:00
用抓包工具( wireshark,tcpdump )看看发的到底对不对,如果发送没问题就查接收端
barbery
2019-07-03 17:13:51 +08:00
额 为什么不直接用 http.PostForm 呢
noahsophie
2019-07-03 17:14:13 +08:00
@ben1024 不行,都是空

#Go 客户端
```
client := &http.Client{}
req, err := http.NewRequest(
"POST",
"http://127.0.0.1/login/check",
strings.NewReader("username=admin&password=123456"),
)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
resp, _ := client.Do(req)
defer resp.Body.Close()
```
这样写,php 可以获取到参数,但是 req 我想单独设置 body,而不是放在 NewRequest 里面
baiyi
2019-07-03 17:24:45 +08:00
简单的看了下 http 包,`NewRequest` 这个方法判断了 `body != nil` 来给 req.ContentLength 进行赋值,如果你要是手动改了 body,可能还需要再改下 ContentLength
loading
2019-07-03 17:25:03 +08:00
先用 postman 测试 php 代码部分,这样用一个绝对正确的东西在测试你的 go 代码。
noahsophie
2019-07-03 17:30:29 +08:00
@baiyi 6666 感谢,就是这个问题!
mcfog
2019-07-03 17:32:40 +08:00
很简单啊,既然 NewRequest 工作直接写.Body 不工作,看下 NewRequest 源码就行了
https://golang.org/src/net/http/request.go?s=26724:26793#L792
noahsophie
2019-07-03 17:35:44 +08:00
@mcfog 知道了~
pubby
2019-07-03 17:50:28 +08:00
req 的 body 是拿来接收请求结果的
janxin
2019-07-04 07:52:21 +08:00
@noahsophie 总感觉你这个需求很奇怪啊...

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/579704

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX