【发布时间】: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