1

我正在尝试从 Eclipse 中的黑莓项目连接到 Web 服务。我的 URLConnector 代码如下

import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.ui.component.Dialog;


public class URLConnector 
{
HttpConnection con = null; 
InputStream is = null; 

public URLConnector()   {
    try 
    {
    Dialog.inform("1"); 
    String url = new String("https://webserviceBlahBlah");

    Dialog.inform(con.toString()); 
        int responseCode = con.getResponseCode(); 
        Dialog.inform("3"); 
        if (responseCode != HttpConnection.HTTP_OK) { 
            Dialog.inform("3.5"); 
            System.out.println(responseCode); 
        } 
        is = con.openInputStream(); 
        byte[] responseData = new byte[10000]; 
        int length = 0; 
        Dialog.inform("4"); 
        StringBuffer rawResponse = new StringBuffer(); 
        while (-1 != (length = is.read(responseData))) { 
            Dialog.inform("5"); 
            rawResponse.append(new String(responseData, 0, length)); 
        } 
        final String result = rawResponse.toString(); 
        System.out.println(result); 
        Dialog.inform("6"); 
    } 
    catch (Exception ex) 
    { 
        Dialog.inform("ex.getMessage()"); 
        System.out.println(ex.getMessage()); 
    } 
    finally 
    { 
        try { 
            is.close(); 
            is = null; 
            con.close(); 
            con = null; 
            Dialog.inform("8"); 
        } 
        catch(Exception e){
            Dialog.inform("e"); 
        } 
    } 
}

应用程序在 con.getReponse() 调用上挂起。它在黑莓 9800 模拟器上运行。任何帮助将不胜感激,因为我非常卡住

4

3 回答 3

2

getResponseCode() 不应该导致它卡住,因为它只是读取建立连接后得到的响应。我的猜测是它实际上是挂起的连接尝试。如果您正在为 5.0 或更高版本进行开发,请查看ConnectionFactory类以确保正确创建连接。

于 2011-06-10T13:05:04.640 回答
0

詹姆斯,我假设在您打开 MDS 模拟器后,您发现您也遇到了问题,因为您从未打开过连接?

无论如何只是为了给出一个最终的工作解决方案:

    HttpConnection con = null;
    InputStream is = null;
    try {
        System.out.println("1");
        String url = new String("http://myserver.com/index.html");

        //I added these two lines to your code and tested it with my own server and got a 200 RC.
        net.rim.device.api.io.transport.ConnectionFactory cf = new net.rim.device.api.io.transport.ConnectionFactory();
        con = (HttpConnection)cf.getConnection(url).getConnection();

        System.out.println(con.toString());
        int responseCode = con.getResponseCode();
        System.out.println("3 responseCode = " + responseCode);
        if (responseCode != HttpConnection.HTTP_OK) {
            System.out.println("3.5");
            System.out.println(responseCode);
        }

此外,如果您必须支持 BBJava 5.0 减号,您可以查看:http ://www.versatilemonkey.com/HttpConnectionFactory.java 。它不是完美的,但它是开始为 5.0 之前的平台创建连接的好地方。

于 2011-06-10T15:27:15.427 回答
0

也许尝试在 URL 的最后添加 ;deviceside=true ?在我的情况下有所帮助。

于 2011-08-17T00:10:31.940 回答