
#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=") 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 获取不到任何内容
1 ben1024 2019-07-03 17:04:44 +08:00 试试 ```php var_dump($_POST) ``` |
2 lff0305 2019-07-03 17:12:18 +08:00 用抓包工具( wireshark,tcpdump )看看发的到底对不对,如果发送没问题就查接收端 |
3 barbery 2019-07-03 17:13:51 +08:00 额 为什么不直接用 http.PostForm 呢 |
4 noahsophie OP @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=") resp, _ := client.Do(req) defer resp.Body.Close() ``` 这样写,php 可以获取到参数,但是 req 我想单独设置 body,而不是放在 NewRequest 里面 |
5 baiyi 2019-07-03 17:24:45 +08:00 简单的看了下 http 包,`NewRequest` 这个方法判断了 `body != nil` 来给 req.ContentLength 进行赋值,如果你要是手动改了 body,可能还需要再改下 ContentLength |
6 loading 2019-07-03 17:25:03 +08:00 via Android 先用 postman 测试 php 代码部分,这样用一个绝对正确的东西在测试你的 go 代码。 |
7 noahsophie OP @baiyi 6666 感谢,就是这个问题! |
8 mcfog 2019-07-03 17:32:40 +08:00 很简单啊,既然 NewRequest 工作直接写.Body 不工作,看下 NewRequest 源码就行了 https://golang.org/src/net/http/request.go?s=26724:26793#L792 |
9 noahsophie OP @mcfog 知道了~ |
10 pubby 2019-07-03 17:50:28 +08:00 via Android req 的 body 是拿来接收请求结果的 |
11 janxin 2019-07-04 07:52:21 +08:00 @noahsophie 总感觉你这个需求很奇怪啊... |