无法使用Golang从App Engine成功地将有效的JSON数据POST到远程URL。

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

Unable to successfully POST valid JSON data to a remote url from App Engine using Golang

问题

#更新:请参考下面的Alexey的评论中的解决方案


##我正在尝试一个我认为很简单的函数,将一些有效的Json数据发送到远程URL

我尝试了在StackOverflow上找到的与此类似的所有示例,但接收方始终没有收到有效载荷。

我排除了接收方的问题,因为我可以执行以下操作:

curl -XPOST 'http://supersecreturl/mypost' -d '[{"i sware to ritchie":"this json is 100 percent valid"},{"i can even":"copy and paste it into a curl POST request and receive it flawlessly on the remote side"}]'

请帮帮我,我在这里快要疯了。。


  1. /// 这大致是我的代码 - 必须删除有效的URL和JSON内容
  2. func PutArticlesJSON(c appengine.Context, articles []*Articlez) (*http.Response){
  3. url := "http://mysecreturl/mypost"
  4. client := urlfetch.Client(c)
  5. jsonarts, _ := json.Marshal(articles)
  6. c.Debugf(" --- What do we have - %v", string(jsonarts)) /// the appengine log shows exactly valid json at this point, such as:
  7. /*
  8. [{"i sware to ritchie":"this json is 100 percent valid"},{"i can even":"copy and paste it into a curl POST request and receive it flawless on the remote side"}]
  9. */
  10. // 也尝试过这种方式....
  11. //req, err := http.NewRequest("POST", url, strings.NewReader(string(jsonarts)))
  12. //
  13. req, err := http.NewRequest("POST", url, bytes.NewBuffer(string(jsonStr))) /// on the receiving side, the payload is completely empty no matter what I try
  14. req.Header.Set("Content-Type", "application/json")
  15. resp, err := client.Do(req)
  16. if err != nil {
  17. panic(err)
  18. }
  19. defer resp.Body.Close()
  20. body, _ := ioutil.ReadAll(resp.Body)
  21. return resp
  22. }

###############################

  1. #!/usr/bin/env python
  2. #
  3. from flask import Flask
  4. from flask import request
  5. import urllib
  6. import json
  7. app = Flask(__name__)
  8. @app.route('/mypost', methods = ['GET','POST'])
  9. def esput():
  10. datapack = request.form
  11. datastream = request.stream
  12. with open("/tmp/log", "a") as myf:
  13. myf.write(str(datastream))
  14. myf.write(str(datapack))
  15. myf.write("\n")
  16. return "all good"
  17. if __name__ == '__main__':
  18. app.run(threaded=True,host='0.0.0.0',port='333',debug=False)
英文:

#UPDATE: Please see Alexey's comments below for the solution


##I am trying what I thought would be a trivial function to take some valid Json data and post it to a remote url

I've tried every example I could find close to this on StackOverflow, and the receiving side always has an empty payload.

I'm ruling out the receiving side, due to being able to do this:

curl -XPOST 'http://supersecreturl/mypost' -d '[{"i sware to ritchie":"this json is 100 percent valid"},{"i can even":"copy and paste it into a curl POST request and receive it flawlessly on the remote side"}]'

Please help, I'm loosing my mind here..


  1. /// Here is approximately my code - had to remove the valid url and the JSON content
  2. func PutArticlesJSON(c appengine.Context, articles []*Articlez) (*http.Response){
  3. url := "http://mysecreturl/mypost"
  4. client := urlfetch.Client(c)
  5. jsonarts, _ := json.Marshal(articles)
  6. c.Debugf(" --- What do we have - %v", string(jsonarts)) /// the appengine log shows exactly valid json at this point, such as:
  7. /*
  8. [{"i sware to ritchie":"this json is 100 percent valid"},{"i can even":"copy and paste it into a curl POST request and receive it flawless on the remote side"}]
  9. */
  10. // tried this way too....
  11. //req, err := http.NewRequest("POST", url, strings.NewReader(string(jsonarts)))
  12. //
  13. req, err := http.NewRequest("POST", url, bytes.NewBuffer(string(jsonStr))) /// on the receiving side, the payload is completely empty no matter what I try
  14. req.Header.Set("Content-Type", "application/json")
  15. resp, err := client.Do(req)
  16. if err != nil {
  17. panic(err)
  18. }
  19. defer resp.Body.Close()
  20. body, _ := ioutil.ReadAll(resp.Body)
  21. return resp
  22. }

###############################

  1. #!/usr/bin/env python
  2. #
  3. from flask import Flask
  4. from flask import request
  5. import urllib
  6. import json
  7. app = Flask(__name__)
  8. @app.route('/mypost', methods = ['GET','POST'])
  9. def esput():
  10. datapack = request.form
  11. datastream = request.stream
  12. with open("/tmp/log", "a") as myf:
  13. myf.write(str(datastream))
  14. myf.write(str(datapack))
  15. myf.write("\n")
  16. return "all good"
  17. if __name__ == '__main__':
  18. app.run(threaded=True,host='0.0.0.0',port='333',debug=False)

答案1

得分: 1

这里有两个问题:

  1. 尽管你认为你发送的是有效的 JSON,但实际上并不是。
  2. NewBuffer 应该接收 []byte,而不是字符串。

尝试像这样修改代码:

s := [{"i sware to ritchie":"this json is 100 percent valid"},{"i can even":"copy and paste it into a curl POST request and receive it flawless on the remote side"}]

req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(fmt.Sprintf({"data":%s}, s))))

英文:

There are two problems I can see there.

  1. Although you think you're sending a valid Json, you aren't.
  2. NewBuffer should receive []byte, not string

Try it like this:

  1. s := `[{"i sware to ritchie":"this json is 100 percent valid"},{"i can even":"copy and paste it into a curl POST request and receive it flawless on the remote side"}]`
  2. req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(fmt.Sprintf(`{"data":%s}`, s))))

huangapple
  • 本文由 发表于 2016年9月10日 11:00:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/39422084.html
匿名

发表评论

匿名网友

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

确定