Nokia 40Series & HTTPconnection

hi there people ....
am facing a wierd problem with nokia 40 series mobiles ....
i've build a cldc1.0 and MIDP 2.0 mobile application that got an http connection ...
my application works as the following ... it initiate an http connection a recives data and show it on the screen ..... ?
i've tested my appliations on several emulators and devices ... but in the nokia 40 series it works but the http connection gets no data and it doesn't retrive data at all ....
here is the method i use for my http connection ......" note the 4o series only uses WAP gateway"
private String requestUsingGET(String URL) throws IOException{
s1=" ";
HttpConnection c = null;
OutputStream os = null;
InputStream is = null;
StringBuffer b = new StringBuffer();
String request = HttpConnection.POST;
TextBox t = null;
try {
long len = -1;
int ch = 0;
long count = 0;
int rc;
c = (HttpConnection)Connector.open(URL);
c.setRequestMethod(request);
c.setRequestProperty("foldedField",
"first line\r\n second line\r\n third line");
if (request == HttpConnection.POST) {
String m = "Test POST text.";
os = c.openOutputStream();
os.write(m.getBytes());
os.close();
rc = c.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
b.append("Response Code: " + c.getResponseCode() + "\n");
b.append("Response Message: " + c.getResponseMessage() +
"\n\n");
is = c.openInputStream();
if (c instanceof HttpConnection) {
len = ((HttpConnection)c).getLength();
if (len != -1) {
// Read exactly Content-Length bytes
for (int i = 0; i < len; i++) {
if ((ch = is.read()) != -1) {
if (ch <= ' ') {
ch = ' ';
b.append((char) ch);
count ++;
if (count > 200) {
break;
} else {
byte data[] = new byte[100];
int n = is.read(data, 0, data.length);
for (int i = 0; i < n; i++) {
ch = data[i] & 0x000000ff;
b.append((char)ch);
try {
if (is != null) {
is.close();
if (c != null) {
c.close();
} catch (Exception ce) {
     try {
          len = is.available();
     } catch (IOException io) {
io.printStackTrace();
     // Test to make sure available() is only valid while          // the connection is still open.
s1 =b.toString();
t = new TextBox("Http Test", b.toString(), b.length(), 0);
is = null;
c = null;
} catch (IOException ex) {
ex.printStackTrace();
if (c != null) {
try {
String s = null;
if (c instanceof HttpConnection) {
s = ((HttpConnection)c).getResponseMessage();
if (s == null){
s = "No Response message";
s1=s;
t = new TextBox("Http Error", s, s.length(), 0);
} catch (IOException e) {
e.printStackTrace();
String s = e.toString();
if (s == null){
s = ex.getClass().getName();
s1 =s;
t = new TextBox("Http Error", s, s.length(), 0);
try {
c.close();
} catch (IOException ioe) {
// do not over throw current exception
} else {
t = new TextBox("Http Error", "Could not open URL", 128, 0);
} catch (IllegalArgumentException ille) {
// Check if an invalid proxy web server was detected.
t = new TextBox("Illegal Argument",
ille.getMessage(), 128, 0);
if (is != null) {
try {
is.close();
} catch (Exception ce) {; }
if (c != null) {
try {
c.close();
} catch (Exception ce) {; }
return (s1);
}

not all network services allow user programs to open HTTP connections so check with the network operator to confirm Whether HTTP connections are allowed.

Similar Messages

  • Need help with my HttpConnection From Midlet To Servlet...

    NEED HELP ASAP PLEASE....
    This class is supposed to download a file from the servlet...
    the filename is given by the midlet... and the servlet will return the file in bytes...
    everything is ok in emulator...
    but in nokia n70... error occurs...
    Http Version Mismatch shows up... when the pout.flush(); is called.. but when removed... java.io.IOException: -36 occurs...
    also i have posted the same problem in nokia forums..
    please check also...
    http://discussion.forum.nokia.com/forum/showthread.php?t=105567
    now here are my codes...
    midlet side... without pout.flush();
    public class DownloadFile {
        private GmailMidlet midlet;
        private HttpConnection hc;
        private byte[] fileData;
        private boolean downloaded;
        private int lineNumber;
    //    private String url = "http://121.97.220.162:8084/ProxyServer/DownloadFileServlet";
        private String url = "http://121.97.221.183:8084/ProxyServer/DownloadFileServlet";
    //    private String url = "http://121.97.221.183:8084/ProxyServer/Attachments/mark.ramos222/GmailId111d822a8bd6f6bb/01032007066.jpg";
        /** Creates a new instance of DownloadFile */
        public DownloadFile(GmailMidlet midlet, String fileName) throws OutOfMemoryError, IOException {
            System.gc();
            setHc(null);
            OutputStream out = null;
            DataInputStream is= null;
            try{
                setHc((HttpConnection)Connector.open(getUrl(), Connector.READ_WRITE));
            } catch(ConnectionNotFoundException ex){
                setHc(null);
            } catch(IOException ioex){
                ioex.printStackTrace();
                midlet.alertScreen = new AlertScreen("Error C1", ioex.toString(),
                        null, AlertType.ERROR);
                midlet.alertScreen.setTimeout(Alert.FOREVER);
                midlet.display.setCurrent(midlet.alertScreen);
            try {
                if(getHc() != null){
                    getHc().setRequestMethod(HttpConnection.POST);
                    getHc().setRequestProperty("Accept","*/*");
                    getHc().setRequestProperty("Http-version","HTTP/1.1");
                    lineNumber = 1;
                    getHc().setRequestProperty("CONTENT-TYPE",
                            "text/plain");
                    lineNumber = 2;
                    getHc().setRequestProperty("User-Agent",
                            "Profile/MIDP-2.0 Configuration/CLDC-1.1");
                    lineNumber =3;
                    out = getHc().openOutputStream();
                    lineNumber = 4;
                    PrintStream pout = new PrintStream(out);
                    lineNumber = 5;
                    pout.println(fileName);
                    lineNumber = 6;
    //                pout.flush();
                    System.out.println("File Name: "+fileName);
                    lineNumber = 7;
                    is = getHc().openDataInputStream();
                    long len = getHc().getLength();
                    lineNumber = 8;
                    byte temp[] = new byte[(int)len];
                    lineNumber = 9;
                    System.out.println("len "+len);
                    is.readFully(temp,0,(int)len);
                    lineNumber = 10;
                    setFileData(temp);
                    lineNumber = 11;
                    is.close();
                    lineNumber = 12;
                    if(getFileData() != null)
                        setDownloaded(true);
                    else
                        setDownloaded(false);
                    System.out.println("Length : "+temp.length);
                    midlet.setAttachFile(getFileData());
                    lineNumber = 13;
                    pout.close();
                    lineNumber = 14;
                    out.close();
                    lineNumber = 15;
                    getHc().close();
            } catch(Exception ex){
                setDownloaded(false);
                ex.printStackTrace();
                midlet.alertScreen = new AlertScreen("Error C2+ line"+lineNumber,
                        ex.toString()+
                        " | ",
                        null, AlertType.ERROR);
                midlet.alertScreen.setTimeout(Alert.FOREVER);
                midlet.display.setCurrent(midlet.alertScreen);
        public HttpConnection getHc() {
            return hc;
        public void setHc(HttpConnection hc) {
            this.hc = hc;
        public String getUrl() {
            return url;
        public void setUrl(String url) {
            this.url = url;
        public byte[] getFileData() {
            return fileData;
        public void setFileData(byte[] fileData) {
            this.fileData = fileData;
        public boolean isDownloaded() {
            return downloaded;
        public void setDownloaded(boolean downloaded) {
            this.downloaded = downloaded;
    }this is the midlet side with pout.flush();
    showing Http Version Mismatch
    public class DownloadFile {
        private GmailMidlet midlet;
        private HttpConnection hc;
        private byte[] fileData;
        private boolean downloaded;
        private int lineNumber;
    //    private String url = "http://121.97.220.162:8084/ProxyServer/DownloadFileServlet";
        private String url = "http://121.97.221.183:8084/ProxyServer/DownloadFileServlet";
    //    private String url = "http://121.97.221.183:8084/ProxyServer/Attachments/mark.ramos222/GmailId111d822a8bd6f6bb/01032007066.jpg";
        /** Creates a new instance of DownloadFile */
        public DownloadFile(GmailMidlet midlet, String fileName) throws OutOfMemoryError, IOException {
            System.gc();
            setHc(null);
            OutputStream out = null;
            DataInputStream is= null;
            try{
                setHc((HttpConnection)Connector.open(getUrl(), Connector.READ_WRITE));
            } catch(ConnectionNotFoundException ex){
                setHc(null);
            } catch(IOException ioex){
                ioex.printStackTrace();
                midlet.alertScreen = new AlertScreen("Error C1", ioex.toString(),
                        null, AlertType.ERROR);
                midlet.alertScreen.setTimeout(Alert.FOREVER);
                midlet.display.setCurrent(midlet.alertScreen);
            try {
                if(getHc() != null){
                    getHc().setRequestMethod(HttpConnection.POST);
                    getHc().setRequestProperty("Accept","*/*");
                    getHc().setRequestProperty("Http-version","HTTP/1.1");
                    lineNumber = 1;
                    getHc().setRequestProperty("CONTENT-TYPE",
                            "text/plain");
                    lineNumber = 2;
                    getHc().setRequestProperty("User-Agent",
                            "Profile/MIDP-2.0 Configuration/CLDC-1.1");
                    lineNumber =3;
                    out = getHc().openOutputStream();
                    lineNumber = 4;
                    PrintStream pout = new PrintStream(out);
                    lineNumber = 5;
                    pout.println(fileName);
                    lineNumber = 6;
                    pout.flush();
                    System.out.println("File Name: "+fileName);
                    lineNumber = 7;
                    is = getHc().openDataInputStream();
                    long len = getHc().getLength();
                    lineNumber = 8;
                    byte temp[] = new byte[(int)len];
                    lineNumber = 9;
                    System.out.println("len "+len);
                    is.readFully(temp,0,(int)len);
                    lineNumber = 10;
                    setFileData(temp);
                    lineNumber = 11;
                    is.close();
                    lineNumber = 12;
                    if(getFileData() != null)
                        setDownloaded(true);
                    else
                        setDownloaded(false);
                    System.out.println("Length : "+temp.length);
                    midlet.setAttachFile(getFileData());
                    lineNumber = 13;
                    pout.close();
                    lineNumber = 14;
                    out.close();
                    lineNumber = 15;
                    getHc().close();
            } catch(Exception ex){
                setDownloaded(false);
                ex.printStackTrace();
                midlet.alertScreen = new AlertScreen("Error C2+ line"+lineNumber,
                        ex.toString()+
                        " | ",
                        null, AlertType.ERROR);
                midlet.alertScreen.setTimeout(Alert.FOREVER);
                midlet.display.setCurrent(midlet.alertScreen);
        public HttpConnection getHc() {
            return hc;
        public void setHc(HttpConnection hc) {
            this.hc = hc;
        public String getUrl() {
            return url;
        public void setUrl(String url) {
            this.url = url;
        public byte[] getFileData() {
            return fileData;
        public void setFileData(byte[] fileData) {
            this.fileData = fileData;
        public boolean isDownloaded() {
            return downloaded;
        public void setDownloaded(boolean downloaded) {
            this.downloaded = downloaded;
    }here is the servlet side...
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            if(request.getMethod().equals("POST")){
                BufferedReader dataIN = request.getReader();
                String fileName = dataIN.readLine();
                File file = new File(fileName);
                String contentType = getServletContext().getMimeType(fileName);
                response.setContentType(contentType);
                System.out.println("Content Type: "+contentType);
                System.out.println("File Name: "+fileName);
                int size = (int)file.length()/1024;
                if(file.length() > Integer.MAX_VALUE){
                    System.out.println("Very Large File!!!");
                response.setContentLength(size*1024);
                FileInputStream fis = new FileInputStream(fileName);
                byte data[] = new byte[size*1024];
                fis.read(data);
                System.out.println("data lenght: "+data.length);
                ServletOutputStream sos = response.getOutputStream();
                sos.write(data);
    //            out.flush();
            }else{
                response.setContentType("text/plain");
                PrintWriter out = response.getWriter();
                BufferedReader dataIN = request.getReader();
                String msg_uid = dataIN.readLine();
                System.out.println("Msg_uid"+msg_uid);
                JDBConnection dbconn = new JDBConnection();
                String fileName = dbconn.getAttachment(msg_uid);
                String[] fileNames = fileName.split(";");
                int numFiles = fileNames.length;
                out.println(numFiles);
                for(int i = 0; i<numFiles; i++){
                    out.println(fileNames);
    out.flush();
    out.close();
    Message was edited by:
    Mark.Ramos222

    1) Have you looked up the symbian error -36 on new-lc?
    2) Have you tried the example in the response on forum nokia?
    3) Is the address "121.97.220.162:8084" accessible from the internet, on the device, on the specified port?

  • Problem with openInputStream (nokia 6233)

    Hi,
    I am a beginner in J2ME.
    I try to make a connection on my nokia 6233 but the connection failed on openInputStream() with Exception.
    I use the following code:
    =================================================
    String url = "http://www.javacourses.com/hello.txt";
    InputStream is = null;
    HttpConnection hc = null;
    try {
    hc = (HttpConnection)Connector.open(url);
    is = hc.openInputStream();
    catch (IOException e) {
    =================================================
    the connection with hc = (HttpConnection)Connector.open(url) is OK
    the hc.openInputStream() is KO
    Thanks in advance.

    micotn
    Welcome to the forum. Please don't post in old threads that are long dead. When you have a question, please start a topic of your own. Feel free to provide a link to an old thread if relevant.
    I'm locking this thread now.
    db

  • Problem in playing the 3GP in Nokia 6600 mobile...

    Hi,
    I am developing application with MMAPI. I want to play the video file saved in 3GP. It is not supported by the emulator. So i am directly checking with the Nokia 6600. The video is not visible on the screen. Any one please help in this topic. The file size very is small. My coding is as follows:
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.io.*;
    import javax.microedition.media.*;
    import javax.microedition.media.control.*;
    import java.io.*;
    public class PlayVideo extends MIDlet
         private Display display;
         private MyCanvas canvas;
         private Player player;
         private VolumeControl vc;
         private InputStream is;
         private VideoControl vdc;
         private HttpConnection connection;
         private ContentConnection c = null;
         private DataInputStream dis = null;
         public PlayVideo()
              display = Display.getDisplay(this);
              canvas = new MyCanvas(this);
         protected void startApp()
              display.setCurrent(canvas);
              canvas.setFullScreenMode(true);
         protected void pauseApp()
         protected void destroyApp(boolean unconditional)
         class MyCanvas extends Canvas
              private PlayVideo playVideo;
              private int Xposition = 0, Yposition = 0, volume = 30, keyValue = 0, width = 30, count = 0, run = 0, barWidth = 0;
              private int videoCount = 0, delay = 0, keyValueCopy = 0;
              private long[] barValue = new long[100];
              private long mediaDuration = 0, totalDuration = 0, temp = 0, newDuration = 0, startDuration = 0, firstDuration = 0;
              private String error, fileFormat = null, filename = null;
              private Image upImage, downImage;
              private boolean isPause = true, isMute = false, isOptionTwo = false, isOptionThree = false, isRewindMode = false, isForwardMode = false;
              private boolean isHTTP = false, isOptionFour = false, isOptionFive = false, isRunning = false, isError = false;
              public MyCanvas(PlayVideo playVideo)
                   this.playVideo = playVideo;
    /*               try
                        upImage = Image.createImage("/up_arrow.png");
                        downImage = Image.createImage("/dn_arrow.png");
                   catch(Exception error)
                        System.out.println("Error is = "+error);
    //               thread.start();
              public void setMute()  //Setting sound in Mute
                   try
                        vc = (VolumeControl) player.getControl("VolumeControl");
                        vc.setMute(true);
                   catch (Exception e)
                        System.out.println("Error in setMute() = "+e);
              public void setUnmute()  //Setting sound to ReMute
                   try
                        vc = (VolumeControl) player.getControl("VolumeControl");
                        vc.setMute(false);
                   catch (Exception e)
                        System.out.println("Error in setUnmute() = "+e);
              public void playVideoFile(Graphics graphics)  //Playing video file from the local path
                   try
                        filename = "02.3gp";
                        fileFormat = TypeOfFile(filename);
                        fileFormat = "video/" + fileFormat;
                        is = getClass().getResourceAsStream(filename);//  To play given file from jar file
                        player = Manager.createPlayer(is, fileFormat);
                        player.realize();
                        vdc = (VideoControl) player.getControl("VideoControl");
                        if(vdc != null)
                             vdc.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
                             vdc.setDisplayLocation(5, 25); //Setting location for video
                             vdc.setVisible(true); //Setting visible
                             player.start(); //Start playing
                             graphics.drawString("Now playing . . .", 5, getHeight()-24, Graphics.LEFT | Graphics.BASELINE);
                   catch(Exception e)
                        error = "Error: "+e;
                        graphics.drawString(error, 5, getHeight()-24, Graphics.LEFT | Graphics.BASELINE);
              public String TypeOfFile(String filename)
                   String filetype = null;
                   filename = filename.toLowerCase();
                   int positionFrom = filename.indexOf(".") + 1;
                   int positionTo = filename.length();
                   String extension = filename.substring(positionFrom, positionTo);  //Splitting the string
                   if (extension.equals("mpg"))
                        filetype = "mpeg";
                   else if (extension.equals("mp3"))
                        filetype = "mp3";
                   else if (extension.equals("mp4"))
                        filetype = "mp4";
                   else if (extension.equals("3gp"))
                        filetype = "3gpp";
                   else if (extension.equals("aac"))
                        filetype = "aac";
                   else if (extension.equals("wma"))
                        filetype = "x-ms-wma";
                   else if (extension.equals("mpeg4"))
                        filetype = "mpeg4";
                   else if (extension.equals("gif"))
                        filetype = "gif";
                   else if (extension.equals("jts"))
                        filetype = "x-tone-seq";
                   else if (extension.equals("wav"))
                        filetype = "x-wav";
                   else if (extension.equals("au"))
                        filetype = "x-au";
                   else if (extension.equals("amr"))
                        filetype = "x-amr";
                   else if (extension.equals("awb"))
                        filetype = "amr-wb";
                   else if (extension.equals("mid"))
                        filetype = "midi";
                   return filetype;
              public void paint(Graphics graphics)
                   if(keyValue == 51)
                        playVideoFile(graphics);
              public void keyPressed(int keyCode)
                   keyValue = keyCode;
                   switch(keyCode)
                   case 51:
                        repaint();
                        break;
                   case 35://Exit from the application
                        destroyApp(true);
                                 notifyDestroyed();
                        break;
         }//  end of Canvas
    }//  end of MIDLETRegards,
    G.Dhanalakashmi

    Hi,
    I am trying to install the Oracle Lite suit versioned 5.0.2 for Windows. The RDBMS is Oralce 9i (9.2.0.1). I am able to install the Mobile server. Refering the Installation mannual I am trying to configure and run the mobile serve in either standalone mode or with Oracle HTTP server. In the installation mannual it is mentioned that the HTTPD.conf file for apache http server should be modified to include the wtgapach.conf file from the Oralce Lite ORACLE_HOME\mobile\server\bin folder. On making this change and starting the apache server I am getting the error listed in the post. In the mannual it is mentioned that for standalone mode run the webtogo executable from the bin folder. On doing so I am getting a message
    "D:\oracle\oralite\Mobile\Server\bin>webtogo
    Unrecognized option: -Xrs"
    So currently I am stuck and do not know how to start the mobile server. Please let me know the appropriate steps to start the Mobile server in stadalone as well as with Oracle HTTP server.
    Also as mentioned by you I replaced the wtgapach.conf with wtgias.conf. The warning message which was displaying earlier on start of Apache is now gone but if tried to start the mobile server from the browser it is not working as expected.
    Thanks and Regards,
    Sachin.

  • NOKIA Series 60 Error HTTP Connection

    Hi..
    Im developing a MIDlet that uses a HTTPconnection
    The MIDlet worked fine using the Default emulator (Grayphone and the ColorPhone).
    But when i tried it on NOKIA emulator (Series_60 MIDP_SDK for Symbian OS v 1_0) it couldnt create a connection. It throwed an IOException with Status = -191 message and when i printStackTrace the error i got this :
    java.io.IOException: Status = -191
         at com.symbian.cldc.connection.ConnectionEndPoint.writeBytes(+140)
         at com.symbian.cldc.connection.OutputStream.flush(+23)
         at com.symbian.midp.io.protocol.http.HttpConnection.sendRequest(+101)
         at com.symbian.midp.io.protocol.http.HttpConnection.ensureResponse(+40)
         at com.symbian.midp.io.protocol.http.HttpConnection.openDataInputStream(+15)
         at com.symbian.midp.io.protocol.http.HttpConnection.openInputStream(+4)
         at NetConnect.connect(+303)
         at NetConnect.run(+25)
    I couldnt figure it out what's wrong in the program ?
    B'coz i didnt use NOKIA API for my MIDlet. And can anyone help me where i could find out the meaning of the Status = -191 and how to make it work ??
    I also have tried to test it on real device using NOKIA 7650, and i couldnt make a network connection too. But it work fine on NOKIA 3530 is it because of the Symbian OS or something else?
    I really need help on this..
    Thanx B4
    Regards,
    Bayu

    When running on your device, you are trying to connect to a web server to localhost = Nokia device.
    I suppose you don't have a web server running onto your device.
    The solution might be :
    - make your server ip (or address) available via internet and then try to make the connection
    - or, make your server to be a modem like server, enabling your phone to establish a connection to it, but don't forget to describe to route like table.
    - find an already internet available server on which you can set up your servlet
    Good Look.

  • HttpConnection error on P900

    Hi
    I run the following code on the p900 device.
    this application connects to a url and gets a simple text message then displays it.
    ( this code is a modified example from the core j2me site examples ...)
    it doesn't work.
    on nokia 6310i device it works , also on every emulator I tried .
    I get a java.io.IOException.SymbianOSerror (something like this ...).
    the last debug message I see is :
    "Attempting to create HttpConnection object" . and then the finally related messages.
    what should I do in order to make this work on p900 ?
    package home;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    import javax.microedition.io.*;
    import javax.microedition.io.HttpConnection;
    import java.io.*;
    import java.lang.StringBuffer;
    public class HttpConn extends MIDlet implements CommandListener , Runnable
      private Display display;
      //TextBox tbMain;
      Form tbMain;
      private Command cmExit;
      private String url = "http://www.corej2me.com/midpbook_v1e1/ch14/getHeaderInfo.txt";
      StringBuffer dbgInfo = new StringBuffer();
      StringBuffer strBfr;
      public HttpConn()
        display = Display.getDisplay(this);
        cmExit = new Command("Exit" , Command.SCREEN , 1);
        tbMain = new Form("HTTP Connection");
        tbMain.addCommand(cmExit);
        tbMain.setCommandListener(this);
      public void run()
        try
          processRequest();
        catch (Exception e)
          dbgInfo.append("run : caught Exception\n");
          dbgInfo.append("run : Exception : " + e.getClass().getName());
          dbgInfo.append("run : Exception message : " + e.getMessage());
          dbgInfo.append("run : Exception string : " + e.toString());
          // also, you should probably display the exception on-screen using an alert or form
          // so that you can see it when running on the phone
          Form f = new Form("Error");
          f.append("An error occurred while connecting : ");
          f.append(new String(dbgInfo));
          f.addCommand(cmExit);
          f.setCommandListener(this);
          display.setCurrent(f);
      public void startApp()
        // set a displayable before you start the connection
        Form f = new Form("Connecting");
        f.append("    Connecting ...\n    Please wait");
        display.setCurrent(f);
        // run the connection in a separate thread
        Thread th = new Thread(this);
        // starts a new thread and calls the run() method in it.
        th.start();
      private void processRequest() throws Exception
        HttpConnection http = null;
        InputStream iStrm = null;
        try
          // Create the connection
          dbgInfo.append("Attempting to create HttpConnection object\n");
          http = (HttpConnection) Connector.open(url);
          // Client Request
          // 1) Send request method
          http.setRequestMethod(HttpConnection.GET);
          // 2) Send header information (this header is optional)
          http.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
          //http.setRequestProperty("If-Modified-Since", "Mon, 16 Jul 2001 22:54:26 GMT");
          // If you experience IO problems, try
          // removing the comment from the following line
          http.setRequestProperty("Connection", "close");
          http.setRequestProperty("Cache-Control", "no-transform");
          // 3) Send body/data - No data for this request
          // Server Response
          // 2) Get header information
          if (http.getResponseCode() == HttpConnection.HTTP_OK) {
            // 3) Get data (show the file contents)
            //String str = new String("initial value");
            dbgInfo.append("Attempting to open the input stream\n");
            iStrm = http.openInputStream();
            int length = (int) http.getLength();
            dbgInfo.append("http.getLength() : "+length+"\n");
            if (length != -1)
                // Read data in one chunk
                byte serverData[] = new byte[length];
                dbgInfo.append("Attempting to read da input stream\n");
                iStrm.read(serverData);
                char chars[] = new char[length];
                for (int i = 0 ; i < length ; i++ )
                  chars[i] = (char) serverData;
    dbgInfo.append("Attempting str = new String(serverData)\n");
    strBfr = new StringBuffer(new String(chars));
    dbgInfo.append("end if\n");
    else // Length not available...
    dbgInfo.append(
    "Attempting to read the input stream one char at a time\n");
    ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
    // Read data one character at a time
    int ch;
    while ( (ch = iStrm.read()) != -1)
    bStrm.write(ch);
    dbgInfo.append("Attempting str = new String(bStrm.toByteArray())\n");
    strBfr = new StringBuffer(new String(bStrm.toByteArray()));
    dbgInfo.append("Attempting bStrm.close()\n");
    bStrm.close();
    dbgInfo.append("Attempting tbMain.setString\n");
    tbMain.append("core j2me site file content :\n" + strBfr);
    dbgInfo.append("display.setCurrent(tbMain)\n");
    display.setCurrent(tbMain);
    dbgInfo.append("end else\n");
    finally
    dbgInfo.append("finally\n");
    if (iStrm != null)
    iStrm.close();
    if (http != null)
    http.close();
    dbgInfo.append("out of finally\n");
    public void pauseApp()
    public void destroyApp(boolean unconditional)
    public void commandAction( Command c, Displayable s )
    if ( c == cmExit )
    destroyApp(false);
    notifyDestroyed();

    Guys I finally managed to get a HTTP connection working on my P900. The problem was to do with my Mobile Network SP. It seems that they are limited in intelligence so when you say that you want access to the internet they will set you up to go to a WAP gateway which translates your requests and responses for your handset. I kept getting a -36 Symbian OS error which implied that the connection was being cut, since a the host name was resolved. After I had argued with the Data Support people for my network, explaining to them that WAP is not the a full Internet access, they finally managed to give me the right dns etc entries and my application was successfully able to communicate.
    Hope this helps, I have another problem to do with installing the same applications on the P900i but I will leave that for another forum :)

  • HttpConnection.getResponseCode() return -1

    Hi guy's
    I am developing a midp application which is communicate with server and display the result on the client using HttpConnection.Basically i am from bangalore,India and using Airtel,Vodafone connections for GPRS. My jar file is properly working in the Sony Ericsson models(k800i,k310i) with airtel and vodafone connections. But the same jar file is failed to communicate with server in Nokia models. HttpConnection.getResponseCode() return -1 in Nokia 6020,6070,6300 devices. Even N6030 is also return same value with vodafone. But same time application working fine in another 6030 model with airtel. Please look at my source code below.
    private static String requestToServer(final String url, final String data)throws IOException {
    HttpConnection httpCon = null;
    InputStream inputStream = null;
    String result = null;
    try {
    while (true) {
    httpCon = (HttpConnection) Connector.open(connectionUrl,Connector.READ_WRITE);
    httpCon.setRequestMethod(HttpConnection.POST);
    final String conf = System.getProperty("microedition.configuration");
    final String prof = System.getProperty("microedition.profiles");
    httpCon.setRequestProperty("User-Agent","Profile/" + prof + " Configuration/" + conf);
    writeDataToConnection(httpCon, data);
    if (!isRedirectResponse(httpCon)) {
    break;
    connectionUrl = httpCon.getHeaderField("Location");
    httpCon.close();
    inputStream = httpCon.openInputStream();
    result = readStreamData(inputStream);
    } catch (final ClassCastException e) {
    throw new IllegalArgumentException("Not an HTTP URL"); }
    catch (final IOException e) { throw e; }
    catch (final Exception e) { throw e; }
    finally {
    if (inputStream != null) { inputStream.close(); }
    if (httpCon != null) { httpCon.close(); }
    return result;
    private static void writeDataToConnection(final HttpConnection c, final String data) throws IOException {
    final OutputStream os = c.openOutputStream();
    try {
    final DataOutputStream dos = new DataOutputStream(os);
    dos.writeUTF(data);
    dos.flush();
    catch(IOException e) { throw e; }
    finally { os.close(); }
    private static boolean requestToServer(final HttpConnection httpCon)throws IOException {
    boolean result = false;
    final int conResponseCode = httpCon.getResponseCode();
    switch (conResponseCode) {
    case HttpConnection.HTTP_OK:
    result = false;
    break;
    case HttpConnection.HTTP_MOVED_TEMP:
    if (DEBUG_REDIRECT) {
    System.out.println("Request is redirected"); }
    result = true;
    break;
    default:
    throw new IOException("HTTP response code: " + conResponseCode);
    return result;
    In the Nokia models, the httpCon.getResponseCode() return -1. Can anybody tell me, whats the problem and what the solution for this please.
    Regards,
    Jobin

    use this ---> return new int[]{1,3};

  • Problem with HttpConnection.....Its Urgent

    hi guys
    i m new to this forum.I read many thread in this forum but unable to get the answaer for my problem.
    I m developing application to get the data from the server ,i used Httpconnection for that.Its works fine for maximum 10 minutes on Nokia 60 series emulator baut after that its showas an error message"unable to establish the connection" and 9500 nokia communicator is hang .
    Can any one help me solve this issue ?is there any problem with the Cache Memory or is it due to some other reason.
    Thanks In Advance

    hello,
    i am a quite new comer.
    i tried to establish a network connection with the server from the KToolbar, but an exception named:
    /* error msg
    Exception: java.io.IOException: Error initializing
    HTTP tunnel connection:
    HTTP/1.0 403 Forbidden
    Server: squid/2.5.STABLE1
    Mime-Version: 1.0
    Data: Sun, 28 May 2006 13:00:28 GMT
    Content-Type: text/html
    ContentLength: 1056
    Expires: Sun,28 May 2006 13:00:28 GMT
    X-Squid-Error: ERR_ACCESS_DENIED 0
    X-Cache: MISS from gw03.univdhaka.edu
    Proxy-Connection: close
    had thrown.
    my used code is:
    // HTTPMIDlet.java
    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class HTTPMIDlet extends MIDlet implements CommandListener, Runnable
         private Display mDisplay;
         private Form mMainScreen;
         public HTTPMIDlet()
              mMainScreen = new Form( "HTTPMIDlet" );
              mMainScreen.append( "Press OK to create an HTTP connection." );
              Command exitCommand = new Command( "Exit", Command.EXIT, 0 );
              Command okCommand = new Command( "OK", Command.OK, 0 );
              mMainScreen.addCommand( exitCommand );
              mMainScreen.addCommand( okCommand );
              mMainScreen.setCommandListener( this );
         public void startApp()
              if( mDisplay==null )
              mDisplay = Display.getDisplay( this );
              mDisplay.setCurrent( mMainScreen );
         public void pauseApp()
         public void destroyApp( boolean unconditional )
         // CommandListener method
         public void commandAction( Command c, Displayable s )
              if( c.getCommandType()==Command.EXIT )
                   notifyDestroyed();
              else if( c.getCommandType()==Command.BACK )
                   mDisplay.setCurrent( mMainScreen );
              else if( c.getCommandType()==Command.OK )
                   // Put up a wait screen.
                   Form waitForm = new Form( "Connecting..." );
                   mDisplay.setCurrent( waitForm );
                   // Make the connection
                   Thread t = new Thread( this );
                   t.start();
         // Runnable method
         public void run()
              //String url = "http://wireless.java.sun.com/";
              String url = "http://203.112.196.113/";
              Form resultsForm = new Form( "Results" );
              Command backCommand = new Command( "Back", Command.BACK, 0 );
              resultsForm.addCommand( backCommand );
              resultsForm.setCommandListener( this );
              HttpConnection hc = null;
              InputStream in = null;
              try
                   // Now make a connection to the server.
                   hc = ( HttpConnection )Connector.open( url );
                   if( hc==null )
                   {System.out.println( "HTTP not Connected..." );}
                   // Retrieve the response.
                   in = hc.openInputStream();
                   int length = 256;
                   byte[] raw = new byte[length];
                   int readLength = in.read( raw );
                   String message = new String( raw, 0, readLength );
                   resultsForm.append( message );
              catch( Exception e )
                   resultsForm.append( new StringItem( "Exception: ", e.toString() ) );
              finally
                   if( in!=null )
                        try
                             in.close();
                        catch( IOException ioe )
                   if( hc!=null )
                        try
                             hc.close();
                        catch( IOException ioe )
              mDisplay.setCurrent( resultsForm );
    }pls, help me with some code or cofiguration guide, if necessary.
    i am now completely stuck at this point, coz without network connection i can't proceed.
    i mailed u, as i seen that u already establish a network connection. so pls pls pls help me......
    info:
    OS: WinXP
    API: MIDP2.0, CLDC1.1
    Server: proxy.univdhaka.edu (linux OS)
    thanx in advance...
    bye...

  • Unable to read http response from servlet (on nokia 6630 device)

    I am sending a http GET request to a servlet for getting some response. Though I am able to obtain the response when I run my j2me app on sony phone I am not able to get any response in case of nokia. On being asked for the APN on nokia I do select the correct one and my settings are correct too. Moreover I am able to connect to the servlet without any problems from my nokia device. However when I tried to read from the Input stream the value returned by read() is -1.
    The code works fine on emulator also. Here is the code snippet being used by me. Plz help me solve this problem. Your response shall be definitely appreciated by me.
    Code in servlet:
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {       
            String t_username = request.getParameter("user");
            String t_password = request.getParameter("pass");
            URL url = new URL("http://somehost:80/query.cgi?serv=s1&user=" + t_username + "&pass=" + t_password);
            HttpURLConnection head = (HttpURLConnection)url.openConnection();
            head.connect();
            int contentLen = head.getContentLength();
            System.out.println("content length = " + contentLen); //here I get some content length value as expected
            BufferedReader in = new BufferedReader(new InputStreamReader(head.getInputStream()));
            StringBuffer sb = new StringBuffer(contentLen);
            String data = null;
            final String NEWLINE = "\r\n"; //acts as delimiter for parsing response later in my j2me code
            while((data = in.readLine()) != null)
                sb.append(data).append(NEWLINE);
            sb.append(NEWLINE);
            in.close();
            PrintWriter out = response.getWriter();
            out.print(sb.toString());
            out.flush();
            out.close();
            head.disconnect();
        }Code in J2ME:
    public static byte[] readFromHttpConnection(String p_URL) throws ConnectionNotFoundException, IOException {
            if(p_URL.startsWith("http://") || p_URL.startsWith("https://")) {
                HttpConnection c = null;
                DataInputStream dis = null;   //tried using InputStream also...still value returned by read() is -1
                c = (HttpConnection)Connector.open(p_URL);
                c.setRequestMethod(HttpConnection.GET);
                c.setRequestProperty("Content-Type", "application/octet-stream");
                dis = c.openDataInputStream();   //able to open this stream
                int len = (int)c.getLength();    //here i get len as -1 for both sony and nokia
                byte[] t_data = null;
                if(len > 0)
                    t_data = new byte[len];
                    int offset = 0;
                    int numRead = 0;
                    while((numRead = dis.read(t_data, offset, t_data.length-offset)) > 0) {
                        offset += numRead;
                else //since i get content length as -1 for both sony and nokia, this block is executed, and though
                       //I am able to read data on sony on nokia read() returns value -1 from the start itself
                    ByteArrayOutputStream bs = new ByteArrayOutputStream();
                    int ch;
                    while((ch = dis.read()) != -1)
                        bs.write(ch);
                    t_data = bs.toByteArray();
                dis.close();
                c.close();
                dis = null;
                c = null;
                return t_data;
            return null;
        }Edited by: alprazolam on Oct 16, 2007 6:02 AM
    Edited by: alprazolam on Oct 16, 2007 6:04 AM
    Edited by: alprazolam on Oct 16, 2007 6:07 AM

    Strange, this should be fine. You might want to try a more efficient (and shorter and faster) read code:
    byte[] buffer = new byte[512];
    ByteArrayOutputStream  = new ByteArrayOutputStream();
    int b;
    while((b=dis.read(buffer))!=-1){
      bs.write(buffer,0,b);
    t_data = bs.toByteArray();No need to check for content length, and always fast. I hope this helps...

  • Sending http data via GPRS Nokia 6600

    Hello!
    We are trying to make a multiplayer game over GPRS. The midlet-server application works fine when we were using the emulator. however, when we test it on the real phone, Nokia 6600, it seems that the data being sent by the MIDlet is not received by the server. We have no idea why it's not working and we hope that maybe some of you are familiar with this and might have some input. Could the problem be caused by our service provider?
    I found this post in the forum wherein they recommended the use of GPRS-internet instead of GPRS-wap since wap could probably be blocking the data due to the content-type.
    Is there a way to set the Nokia 6600 to use GPRS-internet instead of GPRS-wap?
    We hope someone could reply as soon as possible.
    Thanks! =)

    Solution I found:
    Normally when you browser through your mobile ,you connect through Access Point or Access Point Name(APN).these normally connect to WAP sites and you browse through them.
    When you want to access your own server (or servlets) from the j2me MIDlet suite you have to have the Access Point Setting to internet access.This you have to get the settings from the service provider of the mobile connection you are using. I am in India and using Hutch so I activated HUTCH_WWW ie "HUTCH ACCESS" Service.
    If this seeting is done your Httpconnection will work fine.
    Hope people who face similar problem will find this helpful.
    If problem persists then please contact me at [email protected]
    Vishwajeet Wadhwa

  • Network Connection in Nokia 3220 help..

    Anybody who tried network connection in Nokia 3220? I already tried HttpConnection, StreamConnection and ContentConnection to download a simple txt file but none of them succeeded :(

    I suspect that the VM is to bussy printing your dots, and has not time to serve other threads.
    Put a delay inside the while loop, I guess it will start working then.

  • How does WTK handle chunked HTTPConnections via POST?

    Hi,
    I am using
    HttpConnection hc = (HttpConnection) Connector.open(url);
    hc.setRequestMethod(hc.POST);
    to send bytes to a PHP-Skript. Header "Content-Length" is set to the exact value. It is greater than 2KB. I found out that:
    a) If you set WTK-Preferences to HTTP/1.0 everything works fine.
    b) But using HTTP/1.1 will get a 441 (Content-Length is missing)-Error from my script.
    -> And the body is split up to chunks. Alongside with this, the WTK will drop my "Content-Length"-Header and replace it with "Transfer-Encoding: chunked". So,.. Eric D. Larson from SUN has wrote a mysterious article ( http://developers.sun.com/techtopics/mobility/midp/questions/chunking/ ), which left huge spaces in understanding this. What`s exactly the WTK doing here? All message-bodys greater than 2KB are forced to split to chunks. But how does the WTK exactly do this? Is there a BUG in WTK?
    As RFC states: chunks must divided with 2 length bytes etc. But the WTK does not do that. It only breaks up the body into chunks and replaces some header! I have tested several servers which are using HTTP/1.1, none of them was able to handle WTKs Requests... But if you are using other Emulators, for e.g. from Nokia (6230, 6230i) then everything works fine, but of course Nokia is sending out no chunks ;-))
    So to add some serious questions:
    1. Do I have do set some special headers if I have to deal with chunked requests? Server has to understand it... Or does WTK correctly and I have to use Tomcat only ;-)
    2. Is there a way to force a midlet to use HTTP/1.0? setRequestProperty("Version", "HTTP/1.0") seems to be ignored.
    3. Does anybody ever sent Bytes >2KB using HTTP/1.1 succesfully to a standard server??
    Hope that someone can help...!

    chunked should go just fine.
    Forget the Content-Length. Never ever set it with a script it you know chunked is used.
    Then: just read the api cods:
    HttpConnection c = null;
             InputStream is = null;
             try {
                 c = (HttpConnection)Connector.open(url);
                 // Getting the InputStream will open the connection
                 // and read the HTTP headers. They are stored until
                 // requested.
                 is = c.openInputStream();
                 // Get the ContentType
                 String type = c.getType();
                 // Get the length and process the data
                 int len = (int)c.getLength();
                 if (len > 0) {
                     byte[] data = new byte[len];
                     int actual = is.read(data);
                 } else {
                     int ch;
                     while ((ch = is.read()) != -1) {
             } finally {
                 if (is != null)
                     is.close();
                 if (c != null)
                     c.close();
             }Should work just fine!

  • HttpConnection throws NullPointerException

    Hi everybody !
    I'm faceing an odd problem here. I have developed an J2ME (MIDP1.0) application that, among other things, needs to comunicate with my server. The application woks fine on the emulator, it even works great on my phone (Nokia 2650) and on my partners phone (Nokia 6610), but when tested on other phones (SonyErricson, Sagem, Motorola, even an smartphone from Nokia, a 7610 i think) it throws a NullPointerException. I've run out of ideeas regading how to solve this. Here's the piece of code that bugs me:
    public void run(){
            Pachet raspuns = null;               
            display.setCurrent(forma);
            progress.setLabel("Trying to connect");       
            try {
                conn = (HttpConnection) Connector.open(URL, Connector.READ_WRITE);
                conn.setRequestMethod( HttpConnection.POST );
                conn.setRequestProperty("Content-Type", "application/vnd.wap.wmlc");
                byte[] dataForSend = deTrimis.getRawData();
                conn.setRequestProperty("Content-Length", ""+dataForSend.length);
                progress.setLabel("Sending request");
                progress.setValue(25);                      
                forma.append("Opening outputstream\n");
                os = conn.openOutputStream();
                forma.append("Sending data\n");           
                os.write( dataForSend );
                forma.append("Flushing data\n");           
                os.flush();      // this throws the exception
                forma.append("Closing stream\n");           
                os.close();    // if i remove the "os.flush()", the exception is thrown here
                forma.append("Getting response code\n");
                int code = conn.getResponseCode(); // if i remove both os.flush() and os.close() the exception is thrown here !!!
                forma.append("Response code = "+code+"\n");                          
                progress.setLabel("Checking response");
                progress.setValue(50);
                if (code != HttpConnection.HTTP_OK){
                     throw new Exception (conn.getResponseMessage()+"("+code+")");
                progress.setLabel("Reading data");
                progress.setValue(75);           
                if (!aborted){
                    dIn = conn.openDataInputStream();               
                    raspuns = new Pachet();
                    raspuns.readPackage(dIn);
                if (!aborted)
                    listener.packageReceived(raspuns);           
            } catch (Exception e) {
                forma.append("Connection failed. Reason: "+e.getMessage());           
                e.printStackTrace();
            } finally{
                cleanUp();
        }I really need to get this working, so could please someone give me a hint.
    Thank you,
    Daniel Comsa.

    Hi
    I solved this problem.
    There is nothing wrong with the device but the connection that we use.
    Our service provider does not provide the pure HTTP connection rather it goes over WAP and thats where the problem comes.
    Cause we attach our header for the server and WAP sticks his header in between , thats why server does not handle the request and consider it as bad request.
    I have commented the following lines for my code to work
    connection.setRequestProperty("User-Agent",
    System.getProperty("microedition.profiles"));
    connection.setRequestProperty("Content-Type",
    "application/octet-stream");
    Regards,
    Sushil

  • Httpconnection via proxy

    I need to use an httpconnection via a proxy server. How do I do this? At the moment I connect without the proxy server and it works fine, but when I try to connect through a proxy server I get HTTP error code 402. How do I specify my username and password so I can connect via the proxy server. I've found plenty of people asking the same question, but no answer has ever been provided. Any ideas?

    I knew exactly what error code 401 meant, but if you search through this forum and the nokia discussion groups you will find nothing but people asking the same question but getting no useful answers. I could point you to at least 30 forum threads. I performed plenty of searches with no useful results. But I'm sure it must be nice to be as intelligent as you.

  • Ioexception on httpconnection

    Hi,
    i�ve developed a program that connects to a server to receive some data from a database. it works fine on almost all of the phone series (nokia, se, samsung...)
    but i figured out some weird problem on motorola phones and o2�s Ice:
    so i wrote a little testmidlet based on my code. this testmidlet does not open the httpconnection and throws an ioexception instead (response empty)
    here�s my code:
        public void run(){
             boolean success      = true;
             HttpConnection conn = null;
             String status = "";
              try{     
                  DataOutputStream os;
                conn = (HttpConnection)Connector.open("http://www.domain.com/", Connector.READ_WRITE);
                   success = (conn.getResponseCode() == HttpConnection.HTTP_OK);
                   if(success){
                        status = "Success!";
                   }else{
                        status = "Failed";
              }catch (Exception e){
                   status = "Failed: "+e.toString();
              try{
                   if(conn!=null)conn.close();               
              }catch(Exception e){
                   status="close conn exc: "+e.toString();
              conn      = null;
              thread      = null;
              midlet.form.append(status);
        } does anyone have a clue what the problem could be?
    cheers,
    k.

    oddly enough, I encountered the same problem with my C55... http connection seems to generate an IO exception everytime...
    try this piece code, it's "only" stream connection, but it works for me...
             * read url via stream connection
            void getViaStreamConnection(String url) throws IOException {
                    StreamConnection c = null;
                    InputStream s = null;
                    StringBuffer b = new StringBuffer();
                    TextBox t = null;
                    try {
                            c = (StreamConnection) Connector.open(url);
                            s = c.openInputStream();
                            int ch;
                            while ((ch = s.read()) != -1) {
                                    b.append((char) ch);
                            System.out.println(b.toString());
                            //  t = new TextBox("status...", b.toString(), 1024, 0);
                    finally { if (s != null) {
                                      s.close();
                      if (c != null) {
                                      c.close();
                            } // display the contents of the file in a text box.
                    //display.setCurrent(t);
                    reply = b.toString();
            }

Maybe you are looking for

  • Upgrading from 10.4.11 to 10.5

    Hi, I have a Mac book pro running 10.4.11 and I'd like to upgrade to at least 10.5 to make it compatible with the iphone 4. I'd like to avoid shelling out the $140 for the Snow leopard box set because I might be replacing my computer within a year an

  • Issue with XML report printing on R12 instance

    Hi, I'm facing issue with printing xml reports on R12 instance and followed the note (How To Print XML Publisher PDF Reports Via The Concurrent Manager:metalink id:338990.1) and configured the pasta printer,still printer output is showing the junk ch

  • CS4 does not open jpegs it generated itself

    I have just spent half a day preparing jpegs from hires psd's, and I have just found out that the jpegs are all corrupt. When I try to open them, I get a warning message: Could not complete your request because an unknown or invalid jpeg marker type

  • PetStore: correct design?

    Just recently I reviewed Pet Store 1.3.1 application by Sun Microsystem, and I found that Sun model the catalog, item, category, and product using combination of Stateless SB, DAO, and simple java bean.. I was quite surprised.. Then I found their rea

  • TimeStamp to String

    Iam using the DB2 data base and from my java program iam calling a db2 procedure. the procedure returns me a String in this format - 2004-06-22 20:21:12.777343. this is a timeStamp in DB2 , but in java iam getting it as a string using rs.getString me