Python Google App Engine Receiving a string in ste

2019-06-14 16:02发布

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条回答
Summer. ? 凉城
2楼-- · 2019-06-14 16:29

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.

查看更多
登录 后发表回答