0

我正在尝试在黑莓平台上发出 http 请求,我的问题是:当我通过 WiFi 建立连接时效果很好,但是当我使用移动网络时它不起作用并且连接冻结

这是我的代码

    public static String getHttpUTFResponse(String url) {
    url = addConnSuffex(url);
    HttpConnection connection = null;
    byte responseData[] = null;
    try {
        connection = (HttpConnection) new ConnectionFactory()
                .getConnection(url).getConnection();
        int len = (int) connection.getLength();
        System.out.println(len);
        if (len != -1) {
            responseData = new byte[len];
            DataInputStream dis;
            dis = new DataInputStream(connection.openInputStream());
            dis.readFully(responseData);
            dis.close();
        }
    } catch (IOException e) {
        System.out.println("Connection Error");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            connection = null;
        }

    }
    if (responseData != null) {
        try {
            return new String(responseData, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    } else {
        return null;
    }
}

public static String addConnSuffex(String url) {
    ServiceBook sb = ServiceBook.getSB();
    ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
    String uid = null;
    if (records == null) {
        return url;
    }
    for (int i = 0; i < records.length; i++) {
        if (records[i].isValid() && !records[i].isDisabled()) {
            if (records[i].getUid() != null
                    && records[i].getUid().length() != 0) {
                if ((records[i].getUid().toLowerCase().indexOf("wifi") == -1)
                        && (records[i].getUid().toLowerCase()
                                .indexOf("mms") == -1)) {
                    uid = records[i].getUid();
                    break;
                }
            }
        }
    }
    if (DeviceInfo.isSimulator()) {
        return url;
    }
    if (uid != null) {
        // open a WAP 2 connection
        url = url + ";deviceside=true;ConnectionUID=" + uid;
        System.out.println("**************** on conn" + url);
    } else {

        url = url + ";deviceside=true;interface=wifi";
        // Consider another transport or alternative action.
    }
    System.out.println("**************** on conn" + url);
    return url;
}

非常感谢

4

1 回答 1

1

对于网络连接,TransportDetective.class 更加充分,可以解决很多与网络相关的问题。

TransportDetective y URLFactory para configurar la conexion a web

建立 HTTP 或套接字连接的不同方法

于 2012-04-11T12:47:27.503 回答