我在处理不返回数据的 HTTP URL 连接时遇到问题。我正在使用的代码如下......它基本上是一个消息传递客户端,此方法获取发送给假用户(机器人)的任何消息,然后我能够操纵消息,查找关键字,并从机器人。
public void getMessages(String bot)
{
xml = "" +
"xmlMessage=<message type=\"comet.get.message.updates\" "
+ "id=\"" + bot + "\" "
+ "password=\"" + password + "\" />";
// Replace spaces (partial url encode).
xml = xml.replace(" ", "%20");
String serverResponse = "";
try
{
// Build URL
url = new URL(botUrl);
request = (HttpURLConnection)url.openConnection();
// Set the Request Method.
request.setRequestMethod("POST");
request.setDoInput(true);
request.setDoOutput(true);
request.setUseCaches(false);
request.setAllowUserInteraction(false);
request.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
out = request.getOutputStream();
writer = new OutputStreamWriter(out, "UTF-8");
writer.write(xml);
writer.close();
String temp = "";
buff = new BufferedReader ( new InputStreamReader ( request.getInputStream() ) );
while ( (temp = buff.readLine()) != null )
{
serverResponse = serverResponse + temp;
}
// XML RESPONSE EXAMPLE
// xml = "- <message type=\"comet.message.updates\" id=\"chalkboard.status@fdq.att.com\" count=\"2\">z" +
// "- <contact id=\"jy5740\" />" +
// "<statement text=\"test\" from=\"jy5740\" />" +
// "<statement text=\"testing 123\" from=\"jy5740\" />" +
// "</contact>" +
// "</message>";
}
catch (MalformedURLException ex)
{
System.out.println("Bad URL: " + ex);
}
catch (IOException ex)
{
System.out.println("Connection error: " + ex);
}
// do stuff with the serverResponse string
如果在方法调用时还没有收到消息,则该方法可以完美运行。问题是自上次检查以来没有任何消息。该方法仅停留在 while 循环中,直到将消息发送到锁定我的应用程序的机器人。如何确定服务器是否没有响应?