我想知道是否可以立即收到从服务器(Servlet)发送到客户端(Andriod)的消息,并且客户端可以注意到该消息并立即响应它?
感谢您的帮助!!
答案 0 :(得分:2)
答案 1 :(得分:0)
答案 2 :(得分:0)
您的问题没有足够的细节。但我想你想问: 当您的应用程序安装并在设备上运行时,您的服务器会发送消息。 当您的设备收到消息时,它会发送响应。
是的,这是可能的。在安装和运行应用程序时,应该从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));
}
--------------------------编辑---------------