开发者

Why is this app blocking?

I just tried some code from the internet and ran it, but it blocked my emulator. The code is:

public void getcontents()
{
HttpConnection c = null;
InputStream is = null;
StringBuffer sb = new StringBuffer();
try
{
  c = (HttpConnection)Connector.open("http://www.java-samples.com",Connec开发者_JAVA百科tor.READ_WRITE, true);
  c.setRequestMethod(HttpConnection.GET); //default
  is = c.openInputStream(); // transition to connected!
  int ch = 0;
  for(int ccnt=0; ccnt < 150; ccnt++) { // get the title.
    ch = is.read();
    if (ch == -1){
      break;
    }
    sb.append((char)ch);
  }
}
catch (IOException x){
 x.printStackTrace();
}
finally{
     try{
       is.close();
          c.close();
     } catch (IOException x){
          x.printStackTrace();
     }
}
System.out.println(sb.toString());
}

I called the function with an OK command.

The emulator got blocked until I killed the process. How do I solve this?


Try stepping through the code in the debugger. Or at the very least add some log statements. My guess is that the stream is waiting on data from the HTTP connection and isn't getting flushed but I haven't ran the code to verify that assertion.


The only loop I can see in your code is the for loop, which is finite (no more that 150 iterations), so that would not make the code execute indefinitely.

What I would suggest is place a number of debug output statements (output to a console or even dialog box alerts) at various points through the code. This will help you work out which line of code is causing the problem. For instance, if you put a line before and after the for loop and, when executing, only the first one is displayed, you know your problem is somewhere within the loop. You can then narrow it down by putting debug lines within the loop (including the loop number) to find out which line exactly is causing your problem.


Try checking the response code before attempting to read the response body from the server. This will either confirm the connection succeeds or print out the error response. Place the following after the call to Connector.open() :

         if (c.getResponseCode() != HttpConnection.HTTP_OK) {
             throw new IOException("HTTP response code: " + c.getResponseCode());
         } else {
             System.out.println("**Debug** : HTTP_OK received, connection established");
         }

If running the code then gives no output of either the exception or the HTTP confirmation then you are likely blocking on the connection attempt (check your emulator's connectivity to the internet). If you do get the HTTP_OK then you are likely blocking on the server's HTTP response, or lack thereof. Posting a comment with your results would be a good idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜