黑莓HttpConnection概率在模拟器中运行

时间:2012-02-06 13:40:30

标签: blackberry httpconnection getresponse

我想调用一个url并从我的Blackberry App中获取来自url的响应数据。为此,我使用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,我测试过我可以在浏览器中打开任何网站。我的代码有什么问题?

4 个答案:

答案 0 :(得分:2)

最好阅读有关BlackBerry基础架构中的网络的信息。请查看BlackBerry文档。

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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

当您在黑莓手机中打开http连接时 "http://www.google.com" 还应该包含连接suffix.so ur url成为形式 "http://www.google.com"+connectionsuffix

如果你有正常的gprs包,那么你的网址就会变成 “http://www.google.com” + “;装置侧=真”

相关问题