How to call HTTP URL using wifi in J2ME code for BlackBerry 5.0 and above?

爱⌒轻易说出口 提交于 2019-11-29 16:23:22

Check this way:

HttpConnection conn = null;
String URL = "http://www.myServer.com/myContent;deviceside=true;interface=wifi";
conn = (HttpConnection)Connector.open(URL);

source

Nate

Making Connections

Rafael's answer will certainly work if you know you'll only be using Wi-Fi.

However, if you only need to support BlackBerry OS 5.0 - 7.1, I would recommend that you do use the ConnectionFactory. Normally, you will not limit your code to only using one transport. You'll normally support (almost) any transport the device has, but you may want to code your app to choose certain transports first.

For example,

class ConnectionThread extends Thread
{
    public void run()
    {
        ConnectionFactory connFact = new ConnectionFactory();
        connFact.setPreferredTransportTypes(new int[] { 
                TransportInfo.TRANSPORT_TCP_WIFI,
                TransportInfo.TRANSPORT_BIS_B,
                TransportInfo.TRANSPORT_MDS,
                TransportInfo.TRANSPORT_TCP_CELLULAR
        });
        ConnectionDescriptor connDesc;
        connDesc = connFact.getConnection("http://www.google.com");
        if (connDesc != null)
        {
            HttpConnection httpConn;
            httpConn = (HttpConnection)connDesc.getConnection();
            try
            {
                // TODO: set httpConn request method and properties here!
                final int iResponseCode = httpConn.getResponseCode();
                UiApplication.getUiApplication().invokeLater(new Runnable()
                {
                    public void run()
                    {
                        Dialog.alert("Response code: " + 
                                Integer.toString(iResponseCode));
                    }
                });
            } 
            catch (IOException e) 
            {
                System.err.println("Caught IOException: " 
                        + e.getMessage());
            }
        }
    }
}    

will choose the Wi-Fi transport if Wi-Fi is available, but use the GPRS connection if it isn't. I think this is generally considered best practice for the 5.0+ devices.

Request Properties

This code

conn.setRequestProperty("Content-Length", "application/x-www-form-urlencoded");

is not right. Content-Length should be the size, in bytes, of your HTTP POST parameters. See an example here.

Threading

Remember that making network connections is slow. Do not block the user interface by running this code on the main/UI thread. Put your code into a background thread to keep the UI responsive while you request remote content.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!