2012-02-06 67 views
0

我想调用一个url,并从我的黑莓应用程序的URL获取响应数据。为此,我使用HttpConnection。这里是我使用的代码:在黑莓HttpConnection概要在模拟器中运行

import net.rim.device.api.ui.container.MainScreen; 
import net.rim.device.api.ui.UiApplication; 
import net.rim.device.api.ui.component.LabelField; 
import net.rim.device.api.ui.component.Dialog; 

import javax.microedition.io.Connector; 
import javax.microedition.io.ContentConnection; 
import javax.microedition.io.HttpConnection; 
import java.io.DataInputStream; 
import java.io.IOException; 

public class TestApp extends UiApplication { 

    private MainScreen _mainScreen; 

    private static TestApp _app; 

    public TestApp(){ 
     _mainScreen = new MainScreen(); 

     LabelField testField = new LabelField("hello world"); 

     _mainScreen.add(testField); 

     pushScreen(_mainScreen); 

     HttpConnection c = null; 
     DataInputStream dis = null; 

     try { 
     System.out.println("0"); 
     c = (HttpConnection)Connector.open("http://www.google.com"); 

     System.out.println("1"); 
     int rc = c.getResponseCode(); 
     System.out.println("2"); 
     if (rc != HttpConnection.HTTP_OK) { 
      throw new IOException("HTTP response code: " + rc); 
     } 
     System.out.println("3"); 
     dis = c.openDataInputStream(); 
     System.out.println("4"); 
     int len = (int)c.getLength(); 
     if (len > 0) { 
      byte[] data = new byte[len]; 
      dis.readFully(data); 
     } else { 
      int ch; 
      while ((ch = dis.read()) != -1) { 
       //... 
      } 
     } 
     } catch(Exception e){ 
      e.printStackTrace(); 
     }finally { 

      try { 
       if (dis != null) 
        dis.close(); 
       if (c != null) 
        c.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      catch(NullPointerException e) { 
       e.printStackTrace(); 
      } 
     } 

    } 

    public static void main(String[] args) { 
     _app = new TestApp(); 
     _app.enterEventDispatcher(); 

    } 
} 

当我尝试运行模拟器的代码,我得到“0”,那么“1”之后,经过很长一段时间“没有堆栈跟踪”是一个出现调试窗口,只要文本出现,带有文本的关卡应用程序就会在模拟器屏幕中可见。在模拟器的互联网连接中没有问题,我已经设置了Wi-Fi,并且我已经测试过可以在浏览器中打开任何网站。我的代码中有什么问题?

回答

1

MDS必须启动互联网访问,它将作为模拟器和桌面互联网连接之间的接口。

2

最好阅读有关BlackBerry基础结构的网络。请看看BlackBerry文档。

为了让您的代码能够快速工作 - 只需为请求的网址添加后缀 - “; interface = wifi”即可通过WiFi运行,或者使用“deviceside = false”通过无线电访问。因此,您的原始网址将为“http://www.google.com; deviceside = false”或“http://www.google.com; interface = wifi”。

2

也许你应该显示屏幕,然后产生一个工作线程来完成连接。无论如何,您应该在OS> = 5.0中使用ConnectionFactory,以避免之前版本中管理此问题所需的“后缀的后缀”。另请注意,失败的连接通常需要2分钟才能超时。

+1

你真的应该(不,也许)在一个单独的线程上运行http获取。你所做的是让事件线程(因此OS)阻塞等待getResponseCode()返回。自从您阻止操作系统后,它可能永远不会执行此操作。 – Richard 2012-02-07 17:30:22

0

,当你在黑莓您的网址打开http连接 "http://www.google.com" 还应该包含连接suffix.so乌尔URL成为形式的 "http://www.google.com"+connectionsuffix

,如果你有那么正常的GPRS收拾你的网址成为 “http://www.google.com” + “; deviceside = true”