我在处理不返回数据的HTTP URL连接时遇到问题。我正在使用的代码如下......它基本上是一个消息传递客户端,这个方法获取发送给假用户(bot)的任何消息,然后我能够操纵消息,寻找关键词,并从机器人。
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循环中,直到将消息发送到机器人锁定我的应用程序。如何确定服务器是否没有响应?
答案 0 :(得分:1)
彗星的点是“长轮询” - 您提出请求,直到有真实的响应或者超时才会完成。换句话说,如果没有消息,我希望readLine
的呼叫能够长时间阻止。
如果您需要提出不会花费很长时间才能超时的请求,您需要在某处指定超时(可能在HTTP级别,可能在XML内容中)或使用不同的调用开始 - 可能有一种不同类型的消息用于非挂起请求。
答案 1 :(得分:0)
不知道,但这是我的HTTP Post代码:
HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(UPLOAD_URL); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try { reqEntity.addPart("param1", new StringBody("yes")); reqEntity.addPart("param2", new StringBody("no")); httppost.setEntity(reqEntity); LOG.debug("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); String urlImageShack = null; if (resEntity != null) { // XML returned by Imageshack String page = EntityUtils.toString(resEntity); LOG.debug("It return: " + page); }