【问题标题】:Python Google App Engine Receiving a string in stead of JSON objectPython Google App Engine 接收字符串而不是 JSON 对象
【发布时间】:2013-03-23 17:17:54
【问题描述】:

我正在使用下面的脚本从 android 向服务器发送 HTTP POST 请求

            URI website = new URI("http://venkygcm.appspot.com");

            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost(website);

            request.setHeader("Content-Type", "application/json");

            String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());

            JSONObject obj = new JSONObject();
            obj.put("reg_id","Registration ID sent to the server"); 
            obj.put("datetime",currentDateTimeString);

            StringEntity se = new StringEntity(obj.toString());
            request.setEntity(se);
            HttpResponse response = client.execute(request);

            String out = EntityUtils.toString(response.getEntity()); 

由于我发送了一个 JSON 对象,我必须在服务器中接收一个 JSON 对象。相反,我得到一个包含正文数据的字符串。服务器是用 Python Google App Engine 制作的。

 import webapp2

class MainPage(webapp2.RequestHandler):
    def post(self):
        self.response.out.write(" This is a POST Request \n")
        req = self.request
        a = req.get('body')
        self.response.out.write(type(a))

app = webapp2.WSGIApplication([('/', MainPage)], debug=True)

我尝试了 AK09 的建议,但我仍然得到一个字符串类型的对象。我的下一步应该是什么?

import webapp2
import json

class MainPage(webapp2.RequestHandler):
    def post(self):
        self.response.out.write("This is a POST Request \n")
        req = self.request
        a = req.get('body')
        b = json.dumps(a)

        self.response.out.write(type(a))
        self.response.out.write(type(b))

app = webapp2.WSGIApplication([('/', MainPage)], debug=True)

【问题讨论】:

  • 是的。这是我第一次在这方面工作。那么你能告诉我 HTTP 是如何工作的,我应该如何继续我想要实现的目标。
  • Venkatesh,您必须在服务器上处理请求并将其解析为 Json。看看这个stackoverflow.com/questions/1171584/…

标签: android python json google-app-engine http-post


【解决方案1】:

这段代码终于成功了

import webapp2
import json

class MainPage(webapp2.RequestHandler):
    def post(self):
        self.response.out.write("This is a POST Request \n")
        req = self.request
        a = req.body
        b = json.loads(a)

        self.response.out.write(b)
        self.response.out.write(b['reg_id'])
        self.response.out.write(b['datetime'])
        self.response.out.write(type(b))

app = webapp2.WSGIApplication([('/', MainPage)], debug=True)

b 根据需要是 List 类型。

【讨论】:

    猜你喜欢
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多