Python Google App Engine Receiving a string in stead of JSON object

跟風遠走 提交于 2019-12-10 12:34:20

问题


I am sending a HTTP POST request from android to a server using the script below

            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()); 

As I have sent a JSON Object, I must receive a JSON Object in the server. Instead I get a string containing the data of the body. The server is made in 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)

I tried what AK09 suggested but i still get a string kind of object. What should be my next step?

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)

回答1:


Finally this code worked

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 comes out to be of the type List as is required.



来源:https://stackoverflow.com/questions/15763660/python-google-app-engine-receiving-a-string-in-stead-of-json-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!