Search code examples
blackberryhttpconnectiongetresponse

Blackberry HttpConnection prob to run in simulator


I want call a url and get the response data from the url from my Blackberry App. For that, I am using HttpConnection. Here is the code I am using:

import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Dialog;

import javax.microedition.io.Connector;
import javax.microedition.io.ContentConnection;
import javax.microedition.io.HttpConnection;
import java.io.DataInputStream;
import java.io.IOException;

public class TestApp extends UiApplication {

   private MainScreen _mainScreen;

   private static TestApp _app;

   public TestApp(){
       _mainScreen = new MainScreen();

       LabelField testField = new LabelField("hello world");

       _mainScreen.add(testField);

       pushScreen(_mainScreen);

       HttpConnection c = null;
       DataInputStream dis = null;

       try {
        System.out.println("0");
        c = (HttpConnection)Connector.open("http://www.google.com");

        System.out.println("1");
        int rc = c.getResponseCode();
        System.out.println("2");
        if (rc != HttpConnection.HTTP_OK) {
            throw new IOException("HTTP response code: " + rc);
        }
        System.out.println("3");
        dis = c.openDataInputStream();
        System.out.println("4");
        int len = (int)c.getLength();
        if (len > 0) {
            byte[] data = new byte[len];
            dis.readFully(data);
        } else {
            int ch;
            while ((ch = dis.read()) != -1) {
                //...
            }
        }
       } catch(Exception e){
           e.printStackTrace();
       }finally {

           try {
                if (dis != null)
                    dis.close();
                if (c != null)
                    c.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            catch(NullPointerException e) {
                e.printStackTrace();
            }
       }

   } 

    public static void main(String[] args) {
         _app = new TestApp();
         _app.enterEventDispatcher();

  }  
}

When I try to run the code in simulator, I am getting '0', then '1' and after that after long time 'No stack trace' is appearing in debug window and as soon as the text is appearing, the level app with the text becomes visible in the simulator screen. There is no problem in the internet connection in simulator, I have set up the Wi-Fi and I have tested that I can open any website in the browser. What is problem in my code?


Solution

  • MDS has to start for internet access, it will work as interface between Simulator and desktop internet connection.