-1

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

            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)
4

1 回答 1

0

最后这段代码起作用了

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 类型。

于 2013-04-02T20:48:14.403 回答