更新:请参阅下面 Alexey 的评论以了解解决方案
我正在尝试一个我认为很简单的函数来获取一些有效的 Json 数据并将其发布到远程 url
我已经尝试了在 StackOverflow 上可以找到的所有与此接近的示例,并且接收方始终有一个空负载。
由于能够做到这一点,我排除了接收方:
curl -XPOST 'http://supersecreturl/mypost' -d '[{"i sware to ritchie":"this json is 100% valid"},{"i can even":"copy and将其粘贴到 curl POST 请求中并在远程端完美接收它"}]'
请帮忙,我在这里失去理智..
/// Here is approximately my code - had to remove the valid url and the JSON content
func PutArticlesJSON(c appengine.Context, articles []*Articlez) (*http.Response){
url := "http://mysecreturl/mypost"
client := urlfetch.Client(c)
jsonarts, _ := json.Marshal(articles)
c.Debugf(" --- What do we have - %v", string(jsonarts)) /// the appengine log shows exactly valid json at this point, such as:
/*
[{"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"}]
*/
// tried this way too....
//req, err := http.NewRequest("POST", url, strings.NewReader(string(jsonarts)))
//
req, err := http.NewRequest("POST", url, bytes.NewBuffer(string(jsonStr))) /// on the receiving side, the payload is completely empty no matter what I try
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
return resp
}
#
#!/usr/bin/env python
#
from flask import Flask
from flask import request
import urllib
import json
app = Flask(__name__)
@app.route('/mypost', methods = ['GET','POST'])
def esput():
datapack = request.form
datastream = request.stream
with open("/tmp/log", "a") as myf:
myf.write(str(datastream))
myf.write(str(datapack))
myf.write("\n")
return "all good"
if __name__ == '__main__':
app.run(threaded=True,host='0.0.0.0',port='333',debug=False)
最佳答案
我在那里看到了两个问题。
- 虽然您认为您发送的是有效的 Json,但实际上不是。
- NewBuffer 应该接收 []字节,而不是字符串
像这样尝试:
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))))
关于json - 无法使用 Golang 从 App Engine 将有效的 JSON 数据成功发布到远程 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39422084/