2013-04-02 25 views
-1

我从Android的使用下面Python的谷歌应用程序引擎接收JSON对象代替字符串

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

脚本发送一个HTTP POST请求到服务器,当我打发一个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) 
+0

是的。这是我第一次为此工作。那么你能告诉我HTTP是如何工作的吗?我应该如何继续我想要达到的目标。 – VenkateshShukla

+0

Venkatesh,在服务器上您必须处理请求并将其解析为Json。看看这个http://stackoverflow.com/questions/1171584/how-can-i-parse-json-in-google-app-engine?rq=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便脱出的要求是类型列表。