3

从模拟器打开一个简单的 HttpConnection 时遇到问题,我已将 deviceside=true 后缀附加到我的 url,但它仍然无法正常工作,我收到一个响应代码为 0 的空 httpconnection。这是给我带来问题的代码:

public void readUrl(){
     HttpConnection conn=null;
        try {
            conn = (HttpConnection) Connector.open("http://www.google.com;deviceside=true");
            conn.setRequestMethod("GET");
             if(conn.getResponseCode()==HttpConnection.HTTP_OK){
                 System.out.println("Create connection sucessfully");
             }

        } catch (ConnectionNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }




        DataInputStream din=null;
        ByteVector responseBytes=null;
        try {
            din = conn.openDataInputStream();
             responseBytes = new ByteVector();
              int i = din.read();
              while (-1 != i) {
                responseBytes.addElement((byte) i);
                i = din.read();
              }
        } catch (IOException e) {
            //TODO: HANDLE EXCEPTIONS
            e.printStackTrace();
        }
        responseBytes.toArray();

我不知道是怎么回事。它假设通过附加 deviceside=true 它应该直接连接。无论如何,我也尝试安装 MDS 服务器并将我的 url 设置为 deviceside=false,但结果是一样的。

现在我使用http://localhost:8080/resources/mypage.html 之类的本地 url 测试了相同的代码,它按预期工作,所以我想知道这是否可能是模拟器配置问题。我该如何解决?

非常感谢。

4

4 回答 4

3

根据我的经验,您需要在使用 MDS 模拟器时附加 ;deviceside=true 。blackberry.com 论坛上有一篇很棒的帖子,向您展示了如何确定应该使用的连接后缀,以及一些关于在 BlackBerry 中使用连接的一般性良好建议。

为了帮助您更轻松地获取请求的内容,您可以使用 IOUtilities 类:

InputStream stream = conn.openInputStream();
String contents = new String(IOUtilities.streamToBytes(stream));
于 2011-04-14T16:54:20.050 回答
2

在模拟器设置选项卡“常规”中,您是否选中了“使用模拟器启动 MDS-CS”?如果是这样,您根本不需要附加任何后缀...

于 2011-04-14T17:39:55.487 回答
2

";deviceside=true" 用于直接 TCP 传输。要使用 MDS 传输,您需要附加“;deviceside=false”。

当您在设备模拟器上运行时,您可以使用 DIRECT TCP 传输,而无需启动 MDS 模拟器。但是,如果您想测试 MDS 传输,则需要在启动设备模拟器之前启动 MDS 模拟器。

于 2011-04-14T19:33:52.643 回答
1

是的,你是对的,使用 deviceside=true 时使用了互联网连接,但是当我使用以下代码时,它似乎是 HttpConnection 类的问题:

public StreamConnection openConnection(){
    StreamConnection conn=null;
    try {
        conn = (StreamConnection) Connector.open(url+";deviceside=true");
        //conn.setRequestMethod(httpMethod);

    } catch (ConnectionNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }

    return conn;


}

它工作正常,所以我想知道一些事情......在黑莓中打开连接时,我应该将代码放在其中以检查响应代码。创建连接后?像上面的代码或打开数据流之后的代码一样:

din = conn.openDataInputStream();

         responseBytes = new ByteVector();
          int i = din.read();
          while (-1 != i) {
            responseBytes.addElement((byte) i);
            i = din.read();
          }

谢谢。

于 2011-04-15T15:43:17.460 回答