英文:
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"}]'
请帮帮我,我在这里快要疯了。。
/// 这大致是我的代码 - 必须删除有效的URL和JSON内容
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"}]
*/
// 也尝试过这种方式....
//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)
英文:
#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..
/// 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)
答案1
得分: 1
这里有两个问题:
- 尽管你认为你发送的是有效的 JSON,但实际上并不是。
- 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.
- Although you think you're sending a valid Json, you aren't.
- NewBuffer should receive []byte, not string
Try it like this:
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))))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论