【发布时间】:2012-03-02 07:44:00
【问题描述】:
我想知道是否可以立即接收从服务器(Servlet)发送到客户端(Andriod)的消息,并且客户端可以注意到该消息并立即响应它?
感谢您的帮助!!
【问题讨论】:
我想知道是否可以立即接收从服务器(Servlet)发送到客户端(Andriod)的消息,并且客户端可以注意到该消息并立即响应它?
感谢您的帮助!!
【问题讨论】:
【讨论】:
您的问题没有足够的细节。但我想你想问: 当您的应用程序安装并在设备上运行时,您的服务器会发送一条消息。 当您的设备收到消息时,它会发送响应。
是的,这是可能的。当您的应用程序安装和运行时,您应该从 onCreate 或 onStart 方法调用您的 servlet。当您的服务器消息收到时,您将再次从您的设备发送消息。 片段:
HttpClient client = new DefaultHttpClient();
String getURL = "http://www.yourserver/servlet";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
//or call another url hit with your message
}
响应接收的第二个请求是
HttpClient client = new DefaultHttpClient();
String postURL = "http://yourserver";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("message", "your message"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
--------------编辑---------------
【讨论】: