如何在JavaME中解决ConnectionNotFoundException

时间:2012-12-23 16:11:39

标签: netbeans java-me io

我正在尝试通过我的Netbeans模拟器上的J2ME应用程序连接到互联网,其中包含以下功能,该功能连接到网页并使用System.out.println()打印出HTML。

function getHTML(String url)
{
    HttpConnection httpConn = null;
    InputStream is = null;
    OutputStream os = null;

    try
    {
        httpConn = (HttpConnection)Connector.open(url);
        int respCode = httpConn.getResponseCode();
        if (respCode == httpConn.HTTP_OK)
        {
            StringBuffer sb = new StringBuffer();
            os = httpConn.openOutputStream();
            is = httpConn.openDataInputStream();
            int chr;
            while ((chr = is.read()) != -1)
                sb.append((char) chr);

            System.out.println(sb.toString());
            os.close();
            is.close();
        }
        else
        {
            System.out.println("Error " + respCode);
        }
        httpConn.close();
    }
    catch(IOException ioex)
    {
        ioex.printStackTrace();
    }
}

但我收到了以下错误;

javax.microedition.io.ConnectionNotFoundException: error 10051 in socket::open
    at com.sun.midp.io.j2me.socket.Protocol.open0(), bci=0
    at com.sun.midp.io.j2me.socket.Protocol.connect(), bci=209
    at com.sun.midp.io.j2me.socket.Protocol.open(), bci=216
    at com.sun.midp.io.j2me.socket.Protocol.openPrim(), bci=4
    at com.sun.midp.io.j2me.http.Protocol.createConnection(), bci=41
    at com.sun.midp.io.j2me.http.Protocol.connect(), bci=41
    at com.sun.midp.io.j2me.http.Protocol.streamConnect(), bci=164
    at com.sun.midp.io.j2me.http.Protocol.startRequest(), bci=7
    at com.sun.midp.io.j2me.http.Protocol.sendRequest(), bci=33
    at com.sun.midp.io.j2me.http.Protocol.sendRequest(), bci=3
    at com.sun.midp.io.j2me.http.Protocol.getResponseCode(), bci=5

我知道我的代码不是问题,因为这曾经在我的旧笔记本电脑上工作,但是因为我在我的新笔记本电脑上安装了Netbeans,所以它没有用。是因为我的互联网连接,我的防火墙设置,还是我在Netbeans中的设置,还是我没有正确安装Netbeans?

1 个答案:

答案 0 :(得分:0)


如果您想发送一些数据并接收资料,请尝试编码

try
{
        httpConn = (HttpConnection)Connector.open(url);
        os = httpConn.openOutputStream();

        //Writing data to os
        os.write(b);        //Here b is a byte array
        os.flush(); 
        int respCode = httpConn.getResponseCode();
        if (respCode == httpConn.HTTP_OK)
        {
            StringBuffer sb = new StringBuffer();

            is = httpConn.openDataInputStream();
            int chr;
            while ((chr = is.read()) != -1)
                sb.append((char) chr);

            System.out.println(sb.toString());

        }
        else
        {
            System.out.println("Error " + respCode);
        }

    }
    catch(IOException ioex)
    {
        ioex.printStackTrace();
    }

    if(os!=null) os.close();
    if(is!=null) is.close();
    if(httpConn!=null) httpConn.close();
    os=null;is=null;httpConn=null;
}