0

我想调用一个 url 并从我的 Blackberry 应用程序的 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

4 回答 4

2

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

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

于 2012-02-06T20:41:03.677 回答
2

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

于 2012-02-06T22:44:21.030 回答
1

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

于 2012-02-07T12:22:03.357 回答
0

当您在黑莓中打开 http 连接时,您的 url "http://www.google.com" 还应该包含连接后缀。所以您的 url 变成了形式 "http://www.google.com"+connectionsuffix

如果你有普通的 gprs 包,那么你的 url 变成“ http://www.google.com ”+”;deviceside=true”

于 2013-07-11T19:48:38.760 回答