Go – http.Post方法返回400 Bad Request,而http.Get似乎可以工作

huangapple go评论83阅读模式
英文:

Go - http.Post method returns 400 Bad Request while http.Get seems to work

问题

使用以下代码:

// fpCode和fpParams是字符串
ingestionBody := strings.NewReader(fpCode+fpParams)
resp, err := http.Post("http://192.168.1.151:8080/ingest?", "text/plain", ingestionBody)

我得到了错误信息:
"HTTP/1.1 POST /ingest" - 400 Bad Request

我不知道我是否正确使用了Post方法(即使在这个答案中,他们似乎以类似的方式使用它。这是我能找到的唯一一个例子,不幸的是Go文档缺乏示例),问题可能出在第二个参数上,它应该是不同的东西(但我也尝试过"text/*"),或者我漏掉了一些重要的东西。

英文:

With the following code:

//fpCode and fpParams are strings
ingestionBody := strings.NewReader(fpCode+fpParams)
resp, err := http.Post("http://192.168.1.151:8080/ingest?", "text/plain", ingestionBody)

I'm getting the error message:
"HTTP/1.1 POST /ingest" - 400 Bad Request

I don't know if I'm not using the Post method right (even when in this answer, they seem to use it in a similar way. Is the only example that I was able to find, unfortunatelly Go documentation lacks of examples), the problem is with the second parameter, which should be something different (but I also tried "text/*") or there is something important that I'm missing.

答案1

得分: 1

如果你正在进行POST请求,你应该使用application/x-www-form-urlencodedmultipart/form-data作为content-type。

最终你需要查看服务器日志来确定请求失败的原因。

你可以尝试使用http.PostForm()代替。

英文:

If you're doing a POST you should probably be using a content-type of application/x-www-form-urlencoded or multipart/form-data.

Ultimately you need to look at the server logs to determine why the request is failing.

You might try <a href="http://golang.org/pkg/net/http/#Client.PostForm">http.PostForm()</a> instead.

答案2

得分: 1

也许你可以尝试使用http.PostForm:

form := url.Values{}
form.Add("field1", a)
form.Add("field2", b)
http.PostForm("http://192.168.1.151:8080/ingest", form)
英文:

Perhpas you can try http.PostForm:

form := url.Values{}
form.Add(&quot;field1&quot;, a)
form.Add(&quot;field2&quot;, b)
http.PostForm(&quot;http://192.168.1.151:8080/ingest&quot;, form)

huangapple
  • 本文由 发表于 2013年2月9日 01:53:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/14778504.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定