立即接收从服务器发送的消息(Servlet到android)
问题描述:
我想知道是否可以立即接收从服务器(Servlet)发送到客户端(Andriod)的消息,并且客户端可以注意到该消息并立即回应它?立即接收从服务器发送的消息(Servlet到android)
感谢您的帮助!
答
您可以。
HAVE A LOOK AT: http://www.softwarepassion.com/android-series-get-post-and-multipart-post-requests/
答
你的问题没有足够的细节很好的教程。但我想你想问: 由于你的应用程序安装并运行在设备上,你的服务器发送一条消息。 由于您的设备收到消息,它会发送响应。
是的,这是可能的。随着应用程序的安装和运行,您应该使用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));
}
--------------------------编辑---------------
对不清楚的问题。我的意思是这条消息是从服务器端发送的,并且是由服务器创建的,例如android设备通过servlet接收来自其他用户的消息 – user1244556 2012-03-02 08:29:23