ConnectionClosedException

Hello

I use the http POST method to send data from BB device.

Sending data is built in a loop (for). There is little break like 1-2 seconds between loops. The problem is that sometimes I can send data in one, sometimes two and sometimes three iterations and then program trying to send in a next iteration of the loop but with following error message:

Tunnel ID = 1mode = FG already referenced by process = post (373)
IOException net.rim.device.api.io.ConnectionClosedException: closed stream

What I am doing wrong. I have to admin that all the connection closes, inputstream, outpustream are closed immediately after each iteration.

I had this problem too, it was caused because I called the method that contains the loop connection twice at the same time! But I guess you checked than before!

Tags: BlackBerry Developers

Similar Questions

  • net.rim.device.api.io.ConnectionClosedException: closed stream

    Hi guys, I'm a ConnectionClosedException: stream is closed when reading an input stream taken after a response received from the side server.

    This problem is on a single device of BB 9860.

    Here is the code:

    DeviceMiniPcProtocol response = null;
    OutputStream outputStream = null;
    InputStream inputStream = null;

    SocketConnection customer = null;

    try {}
    client = (SocketConnection) Connector.open)
    "socket://10.1.1.1:8989; interface = wifi. "
    Connector.READ_WRITE);
    } catch (Exception e) {}
    listener.onErrorReceived (message.getOperation (), "Error connecting to Server");
    }

    If (customer! = null) {}
    try {}
    outputStream = client.openOutputStream ();

    outputStream.write (message.getCommandParsed () .getBytes ());
    outputStream.flush ();
    outputStream.close ();

    Byte [] responseDataLength = new ubyte [5];
    Byte [] responseData;
    int bytesToRead;
    String context;

    inputStream = client.openInputStream ();

    If (inputStream.read (responseDataLength, 0,))
    (responseDataLength.length) > 0) {}
    bytesToRead = Integer.parseInt (new String)
    responseDataLength));
    responseData = new ubyte [bytesToRead];

    If (inputStream.read (responseData, 0, responseData.length) > 0) {}
    Context = new String (responseData);
    Context = CryptoUtils.decrypt (context);

    response = new DeviceMiniPcProtocol();
    response.handleMessage (context);
    }
    }

    inputStream.close ();
    customer. Close();

    listener.onResponseReceived (response);
    } catch (InterruptedIOException e) {}
    listener.onErrorReceived (message.getOperation (),
    "Timeout received');
    } catch (Exception e) {}
    listener.onErrorReceived (message.getOperation (), "Error sending message");
    }
    }

    After this line: If (inputStream.read (responseDataLength, 0, responseDataLength.length) > 0) I get the exception and there is no available bytes to read, but actually, the server returns data to this customer.

    I appreciate the help that you could give me.

    Kind regards

    Jesus

    I found the problem.

    I changed to close the stream and connection in a finally block.

    Thanks anyway!

  • Not connected: net.rim.device.api.io.ConnectionClosedException on HttpConnection.openInputStream

    I am trying to download. AMR file to my server. My code is as follows:

    public byte[] send(byte[] fileBytes) throws Exception
        {
            String boundary = getBoundaryString();
            String endBoundary = "\r\n--" + boundary + "--\r\n";
            HttpConnection hc = null;
            InputStream is = null;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] res = null;
            try
            {
                hc = (HttpConnection) Connector.open(url);
                hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString());
                hc.setRequestMethod(HttpConnection.POST);
                hc.setRequestProperty(HttpProtocolConstants.HEADER_ACCEPT_CHARSET,
                        "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                OutputStream dout = hc.openOutputStream();
                dout.write(boundaryMessage.getBytes());
                dout.write(this.postBytes);
                dout.write(endBoundary.getBytes());
                dout.close();
                int ch;
                is = hc.openInputStream(); //exception raised here
                if(hc.getResponseCode()== HttpConnection.HTTP_OK)
                        {
                    while ((ch = is.read()) != -1)
                    {
                        bos.write(ch);
                    }
                    res = bos.toByteArray();
                    System.out.println("res loaded..");
                         }
                else {
                    System.out.println("Unexpected response code: " + hc.getResponseCode());
                    hc.close();
                    return null;
                }
            }
            catch(IOException e)
            {
                System.out.println("====IOException : "+e.getMessage()+" Class: "+e.getClass());
            }
            catch(Exception e1)
                {
                    System.out.println("====Exception : "+e1.getMessage()+" Class: "+e1.getClass());
                }
            finally
            {
                try
                {
                    if(bos != null)
                        bos.close();
    
                    if(is != null)
                        is.close();
    
                    if(hc != null)
                        hc.close();
                }
                catch(Exception e2)
                {
                    e2.printStackTrace();
                    System.out.println("====Exception : "+e2.getMessage());
                }
            }
            return res;
        }
    

    The line of code highlighted above raises a ConnectionClosedException. Can someone tell me why and what I can do to overcome? Thanks in advance.

    This suggests that the server does not accept your application.  See if you can find what the server thinks is happening.  Check your URL too.

  • net.rim.device.api.io.ConnectionClosedException: Connection closed

    Hello

    I'm "net.rim.device.api.io.ConnectionClosedException: Connection closed" exception so that he was trying to get the response code in the following code snippet. What will be the reason for this exception: -.

    HttpConnection connection=(HttpConnection)Connector.open(url);
            System.out.println("Post-----------------------1");
            connection.setRequestMethod(HttpConnection.POST);
            System.out.println("Post-----------------------2");
            connection.setRequestProperty("Content-Type",aRequest.getContentType());
            System.out.println("Post-----------------------3");
            Hashtable header=aRequest.getHeader();
            if(header!=null)
            {
                Enumeration enumeration =header.keys();
                while(enumeration.hasMoreElements())
                {
                    String headerStr=(String)enumeration.nextElement();
                    String headerValue=(String)header.get(headerStr);
                    //System.out.println("header:"+headerStr+"headerval::"+headerValue);
                    connection.setRequestProperty(headerStr,headerValue);
                }
            }
            System.out.println("Post-----------------------4");
            OutputStream postRequestOutputStream=connection.openOutputStream();
            System.out.println("Post-----------------------4#########");
            postRequestOutputStream.write(aRequest.getPostData());
            System.out.println("Post-----------------------4%%%%%%%");
            postRequestOutputStream.close();
            System.out.println("Post-----------------------5");
            System.out.println("RES CODE:"+connection.getResponseCode());
            InputStream is=connection.openInputStream();
    

    Try opening the InputStream before getResponseCode().

    concerning

  • net.rim.device.api.io.ConnectionClosedException: not connected

    Hello world

    I have problems when making calls POST on my app.

    When I meet first the question above, I fixed it by running the network call in a different thread.

    However, the problem has started again,

    Whenever I'm doing a POST request, my connection returns a response code 0, and I don't know what is causing the connection close. Download the application are works very well as a POST request when a user connects.

    However, for example when a user connects, I get a response code 0.

    I've been on it for a month now and I read many post about this, and yet I found nothing that solve my problem.

    Can someone help me with this.

    Thank you

    I would like to be confident that you are coding is different, because you say this:

    "I noticed that the response code is already 0.

    How many checks the response code are there in the sample that I pointed you to?

    You must complete your writing before you get the response code.  Get the response code means that BlackBerry, sends it the data to the server and gets a response from the server.  Thus, after the getResponseCode(), if you try to do anything other than read the answer, it will fail, as you have described.

    Please see the following Post, and you might find other positions in the interesting Thread:

    http://supportforums.BlackBerry.com/T5/notifications/notifymoderatorpage/message-UID/2867136

  • Download file problem

    package com.blackberry.util.network;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Enumeration;
    import java.util.Hashtable;
    
    import javax.microedition.io.Connector;
    import javax.microedition.io.HttpConnection;
    import javax.microedition.io.file.FileConnection;
    
    import net.rim.device.api.io.http.HttpProtocolConstants;
    import net.rim.device.api.io.transport.ConnectionDescriptor;
    import net.rim.device.api.io.transport.ConnectionFactory;
    import net.rim.device.api.io.transport.TransportInfo;
    import net.rim.device.api.ui.UiApplication;
    
    import com.blackberry.util.Function;
    import com.blackberry.util.StringUtility;
    import com.blackberry.util.log.Logger;
    
    public class NetworkThread extends Thread
    {
        private static final String twoHyphens = "--";
        private static final String Boundary = "****************256176b82bde4478"; //what_hell_is_that
        private static final String lineEnd = "\r\n";
    
        private ObserverInterface _ourObserver;
        private String _targetURL;
        private Hashtable _params;
        private String _fileField;
        private String _fileName;
        private String _fileType;
        private String _fileURI;
        private boolean _stopRequest = false;
    
        private ConnectionFactory cf;
        private Logger log;
        private int[] preferredTransportTypes = {TransportInfo.TRANSPORT_TCP_WIFI, TransportInfo.TRANSPORT_TCP_CELLULAR};
        private int[] disallowedTransportTypes = {TransportInfo.TRANSPORT_BIS_B, TransportInfo.TRANSPORT_MDS, TransportInfo.TRANSPORT_WAP, TransportInfo.TRANSPORT_WAP2};
    
        private long postSize = 0;
    
        public NetworkThread(String requestURL, Hashtable params, String fileField, String fileName, String fileType, String fileURI, ObserverInterface observer)
        {
            super();
    
            log = Logger.getLogger(getClass());
    
            cf = new ConnectionFactory();
            cf.setPreferredTransportTypes(preferredTransportTypes);
            cf.setDisallowedTransportTypes(disallowedTransportTypes);
            cf.setTimeoutSupported(true);
            cf.setAttemptsLimit(10);
            cf.setConnectionTimeout(120000);
    
            _targetURL = requestURL;
            _params = params;
            _fileField = fileField;
            _fileName = fileName;
            _fileType = fileType;
            _fileURI = fileURI;
            _ourObserver = observer;
    
            postSize = getMultipartPostBytesSize(_fileField, _fileName, _fileType, _fileURI);
        }
    
        public void stop()
        {
            observerError(ObserverInterface.CANCELLED, "Cancelled by User");
            _stopRequest = true;
    
            Thread.currentThread().interrupt();
        }
    
        private void observerStatusUpdate(final int status, final String statusString)
        {
            if (!_stopRequest)
            {
                _ourObserver.processStatusUpdate(status, statusString);
            }
        }
    
        private void observerError(int errorCode, String errorMessage)
        {
            if (!_stopRequest)
            {
                _ourObserver.processError(errorCode, errorMessage);
            }
        }
    
        private void observerResponse(byte [] reply)
        {
            if (!_stopRequest)
            {
                _ourObserver.processResponse(reply);
            }
        }
    
        public void run ()
        {
            HttpConnection httpConn = null;
            FileConnection fileConn = null;
            InputStream input = null;
            OutputStream output = null;
            StringBuffer buffer = new StringBuffer();
            StringBuffer responeBuffer = new StringBuffer();
    
            try {
                if ((_targetURL == null) || _targetURL.equalsIgnoreCase("") || (cf == null))
                {
                    if (!_stopRequest)
                    {
                        _ourObserver.processError(ObserverInterface.ERROR, "Target url empty or http connection initial failed!");
                    }
                }
    
                StringBuffer urlBuffer = new StringBuffer(_targetURL);
    
                if ((_params != null) && (_params.size() > 0)) {
                    urlBuffer.append('?');
                    Enumeration keysEnum = _params.keys();
    
                    while (keysEnum.hasMoreElements())
                    {
                        String key = (String) keysEnum.nextElement();
                        String val = (String) _params.get(key);
                        urlBuffer.append(key).append('=').append(val);
    
                        if (keysEnum.hasMoreElements()) {
                            urlBuffer.append('&');
                        }
                    }
                }
    
                ConnectionDescriptor connd = cf.getConnection(urlBuffer.toString());
                String transportTypeName = TransportInfo.getTransportTypeName(connd.getTransportDescriptor().getTransportType());
                httpConn = (HttpConnection) connd.getConnection();
    
                if (httpConn != null)
                {
                    try {
                        httpConn.setRequestMethod(HttpConnection.POST);
                        httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CONNECTION, HttpProtocolConstants.HEADER_KEEP_ALIVE);
                        httpConn.setRequestProperty(HttpProtocolConstants.HEADER_ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                        //httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CACHE_CONTROL,"no-cache, no-store, no-transform");
                        httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, HttpProtocolConstants.CONTENT_TYPE_MULTIPART_FORM_DATA + "; boundary=" + Boundary);
                        httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, Long.toString(postSize));
                        output = httpConn.openOutputStream();
    
                        buffer.append(twoHyphens + Boundary + lineEnd);
                        buffer.append("Content-Disposition: form-data; name=\"" + _fileField + "\"; filename=\"" + _fileName + "\"" + lineEnd);
                        buffer.append("Content-Type: " + _fileType + lineEnd);
                        buffer.append(lineEnd);
                        output.write(buffer.toString().getBytes());
                        observerStatusUpdate(1, "Started");
    
                        fileConn = (FileConnection)Connector.open(_fileURI, Connector.READ);
                        long totalBytes = fileConn.fileSize();
                        if (totalBytes == -1) {throw new IOException("File " + _fileURI + " not available.");}
    
                        long sentBytes = 0;
                        int percentPre = 0;
    
                        input = fileConn.openInputStream();
                        byte[] temp = new byte[1024];
    
                        int len = 0;
    
                        while ((len = input.read(temp)) > -1)
                        {
                            if (_stopRequest)
                            {
                                observerError(ProgressListener.CANCELLED, "User canceled.");
                                return;
                            }
    
                            output.write(temp, 0, len); 
    
                            //Thread.yield();
    
                            sentBytes += len;
                            int percentageFinished = (int) ((sentBytes * 100) / totalBytes);
                            percentageFinished = Math.min(percentageFinished, 99); 
    
                            if (percentageFinished != percentPre)
                            {
                                observerStatusUpdate(percentageFinished, StringUtility.formatSize(sentBytes, 1) + " / " + StringUtility.formatSize(totalBytes, 1));
                            }
    
                            percentPre = percentageFinished;
                        }
    
                        output.write(lineEnd.getBytes());
                        output.write((twoHyphens+Boundary+twoHyphens+lineEnd).getBytes());
    
                        output.flush();
                        output.close();
                    } catch (IOException e)
                    {
                        observerError(ProgressListener.ERROR, "Post data exception: \n\n" + e.getMessage());
                    }
    
                    log.info("HTTP-POST-MULTI (" + transportTypeName + "): " + httpConn.getURL());
    
                    int resCode = 0;
                    String resMessage = "";
    
                    try {
                        resCode = httpConn.getResponseCode();
                        resMessage = httpConn.getResponseMessage();
    
                        log.info("HTTP-POST-MULTI Response: " + resCode + " " + resMessage);
                    } catch (IOException e) {
                        observerError(ProgressListener.ERROR, "get respone code ioexception: \n\n" + e.getMessage());
                    }
    
                    switch (resCode)
                    {
                        case HttpConnection.HTTP_OK:
                        {
                            InputStream inputStream;
                            int c;
    
                            try {
                                inputStream = httpConn.openInputStream();
                                while ((c = inputStream.read()) != -1)
                                {
                                    responeBuffer.append((char) c);
                                }
    
                                inputStream.close();
                            } catch (IOException e)
                            {
                                Function.errorDialog("HTTP_OK ioexception: " + e.toString());
                            }
    
                            observerStatusUpdate(100, "File uploaded.");
    
                            UiApplication.getUiApplication().invokeAndWait(new Runnable()
                            {
                                public void run()
                                {
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {}
                                }
                            });
    
                            observerResponse(responeBuffer.toString().getBytes());
                            break;
                        }
                        case HttpConnection.HTTP_BAD_REQUEST:
                        {
                            InputStream inputStream;
                            int c;
    
                            try {
                                inputStream = httpConn.openInputStream();
                                while ((c = inputStream.read()) != -1)
                                {
                                    responeBuffer.append((char) c);
                                }
    
                                inputStream.close();
                            } catch (Exception e)
                            {
                                Function.errorDialog("HTTP_BAD_REQUEST ioexception: " + e.toString());
                                observerError(ProgressListener.ERROR, e.getMessage());
                            }
    
                            observerError(ProgressListener.ERROR, "File transfer problems!");
    
                            break;
                        }
                        case HttpConnection.HTTP_TEMP_REDIRECT:
                        case HttpConnection.HTTP_MOVED_TEMP:
                        case HttpConnection.HTTP_MOVED_PERM:
                        {
                            observerError(ProgressListener.ERROR, "File transfer moved!");
                            break;
                        }
                        case HttpConnection.HTTP_INTERNAL_ERROR:
                        {
                            observerError(ProgressListener.ERROR, "Internal server error");
                            break;
                        }
                        default:
                            break;
                    }
                }
    
                log.info("HTTP-POST-MULTI Body: " + httpConn.getType() + "(" + responeBuffer.length() + ")");
                log.debug(responeBuffer.toString());
            } catch (Throwable t)
            {
                Function.errorDialog(t.toString());
                log.error("New Thread Throwable: " + t.getMessage());
                t.printStackTrace();
            } finally {
                if (input != null) {try {input.close();} catch (IOException e) {}}
                if (fileConn != null) {try {fileConn.close();} catch (IOException e) {}}
                if (output != null) {try {output.close();} catch (IOException e) {}}
                if (httpConn != null) {try {httpConn.close();} catch (IOException e) {}}
            }
    
            _stopRequest = true;
            _ourObserver = null;
    
            observerStatusUpdate(100, "Finished"); // Tell Observer we have finished
            observerResponse("Succeeded".getBytes());
        }
    
        private long getMultipartPostBytesSize(String name, String fileName, String fileType, String fileURI)
        {
            StringBuffer buffer = new StringBuffer();
            FileConnection fconn = null;
            long fileSize = 0;
    
            /*
             * @multipart post format
             *  --****************256176b82bde4478\r\n
             *  Content-Disposition: form-data; name="uploadfile"; filename="fileName"\r\n
             *  Content-Type: txt/plain\r\n
             *  \r\n
             *  [content bytes of upload file]
             *  \r\n
             *  --****************256176b82bde4478--\r\n
            */
            buffer.append(twoHyphens + Boundary + lineEnd);
            buffer.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"" + lineEnd);
            buffer.append("Content-Type: " + fileType + lineEnd);
            buffer.append(lineEnd);
    
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
            try
            {
                baos.write(buffer.toString().getBytes());
                baos.write(lineEnd.getBytes());
                baos.write((twoHyphens+Boundary+twoHyphens+lineEnd).getBytes());
    
            } catch (IOException e) {
                Function.errorDialog("flush byte data ioexception: " + e.toString());
            }
    
            try {
                fconn = (FileConnection)Connector.open(fileURI);
                fileSize = fconn.fileSize();
                fconn.close();
            } catch (IOException e) {
            }
    
            return baos.toByteArray().length + fileSize;
        }
    }
    

    I use post multipart via httpConnection method to upload files on server (website a service net disk, single file size is limited to 500 MB), I tested the Simulator (9800 Asia, software: 6.0.0.706, platform: 3.0.0.159, network: wifi) and download a large file 40 MB, but when I signed my record of cod and tested on the device (9900 (, software: 7.1.0.1098, platform: 5.1.0.701 network: wifi), I had an interruption during about 3 MB of data download and threw a ConncectionClosedException.

    Here is my proposal, when output.write (filled with all bytes) amount (perhaps 10240 bytes), it will download bytes in the buffer to the server immediately, and waiting for filled with bytes remaining and so on. Download the bytes in the buffer may take a long time to wait, if the ConnectionClosedException is took place during this freeze period?

    If I download a file less than 1 MB on the device, it will be probably successful, Yes, not 100% success rates, I do not know what problem I am facing now

    "I don't have limits of authority to deal with pieces of data on the server.

    You might have problems if you do this on mobile service because they can or can not cut you if you try to upload too many bytes, more WiFi, it should work good Chunking is really useful for recovery reboot only, does not provide all of the extra features.

    «the network indicator in the upper right corner of the device screen will flash several times, until the flash stopped writing bytes will continue progress.»

    OK, not my experience with mobile connections, maybe it works that way with WiFi or using the https protocol, which does not establish the connection at first.

    That being said, I don't think I can help a lot here sorry.

  • Always troubling with HTTPConnection

    Hi all

    I try to call a URL in my api application using HTTPConnection and Connector.open (URL) using my 9800 Simulator. I am still suffering with response code 302 or some exception(connectionclosedexception,timedoutexception) reading response code. Someone please help me how can I get rid of this problem?

    Thanks in advance...

    Exceptions are usually the result of problems, and there is no generic solution for them.  You have to try to determine the circumstances in which they occur, reproduce it and then try to determine a work around.

    Then I suggest that provide you more details on a specific Exception, such as carrier, device, OS level, connection method you try, maybe even a part of the code (but only the bits of relevant link, what you see when you debug and so forth.)  We can address this specific issue in detail.

    But before you give us all this, search the forum for similar problems see if others have reported similar problems (which is more likely).

    The link provided by alishaik786 is unlikely to help, it won't help very definitely not the 302 problem.

  • DataOutputStream HTTP Post rinse and segment the encoding problems

    Hello

    I'm finally back to the question that I had a few months ago, but I can't always solve this

    I used this article to understand how to upload files into pieces of a server: http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800332/800431/How_To _...

    Downloading is easy to implement, but I have problems with the download. I am trying to download a large file into smaller pieces. I tried different options. The one that works best is when I use DataOutputStream and write in there after each small party has been read from the file.

    But when I used the flush() function then he threw OutOfMemoryException()! But only if the file is quite large.

    An example of code:

    InputStream    is = (StreamConnection)Connector.open(url , Connector.READ_WRITE, true);
    HttpConnection c = (HttpsConnection)is;
    
    //set connection parameters
    c.setRequestMethod( HttpConnection.POST );
    c.setRequestProperty( "User-Agent", "MyUserAgent/0.2" );
    
    for( ;; )
    {   if( done ) break;
    
       //i have removed some reading code to simlify example
       out.write( bytedata  , 0 , bytesRead );
       Thread.yield();
    }
    
    out.flush();     //<-- OutOfMemory exception here!
    
    int result = c.getResponseCode();
    
    out.close();
    

    I found that I wasn't the only one to have this problem.

    1: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4212479

    2: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5026745

    I usually have the same code, but only use HTTPConnection for this.

    The solution was to use "Chunked" encoding of the header and appellant hunting every time data is written to the output stream.

    However, it has not worked for me. If I use a stored block coding, I 'ConnectionClosedException' when flush() is used for the first time.

    Here is a code example:

    InputStream    is = (StreamConnection)Connector.open(url , Connector.READ_WRITE, true);
    HttpConnection c = (HttpsConnection)is;
    
    //set connection parameters
    c.setRequestMethod( HttpConnection.POST );
    c.setRequestProperty( "User-Agent", "MyUserAgent/0.2" );
    c.setRequestProperty( HttpProtocolConstants.HEADER_TRANSFER_ENCODING, "chunked" );
    
    for( ;; )
    {
       if( done ) break;
    
       //i have removed some reading code to simlify example
       out.write( bytedata  , 0 , bytesRead );
       Thread.yield();
       out.flush();     //<-- ConnectionClosedException
    }
    
    int result = c.getResponseCode();
    
    out.close();
    

    Here is a screenshot of the at the time of the exception stack trace:

    And here are the details of the exception:

    Now, I honestly don't know what to do next. I tried all sorts of options and choices, but can not get this to work for some reason to download any.

    Tried on BlackBerry JDE and Simulator 4.2.1

    Help, please

    Thank you.

    Thank you, but I think that this was not related to this problem.

    The solution is to use SocketConnection would work on writing data OutputStream and flush(). But only if the Content-Length is calculated with precision and this server application is also properly formatted.

    If there are errors in the POST request, the server would send a message back and ConnectionClosedException appear.

    The best way to resolve these issues is to get a sniffer package good as "Wireshark" and study all the packages with a lot of attention even a small typo can break everything.

    I have another question, but the download itself works with the function flush() as expected on the device and emulator. So I think this can be considered fixed.

  • ListField action listener

    Hi all

    Im trying to create a list with a ListField that contains a list of vectors.

    Now I want to put an action listener to the to the ListField then when somebody cliks something on the list of the application of the captures that.

    I tried to do by adding listfield.setChangeListener, but it does not work

    Here is my code.

    public class ServerSelect extends MainScreen {
        private Main main;
        private ServerList serverlist;
        private Bitmap online, offline;
        private Vector list;
        private ListField listfield;
        private ListCallback callback;
    
        public ServerSelect(Main main)
        {
            this.main = main;
            online = Bitmap.getBitmapResource("talking.jpg");
            offline = Bitmap.getBitmapResource("not_talking.jpg");
            list = new Vector();
            listfield = new ListField();
            callback = new ListCallback();
            listfield.setCallback(callback);
            add(listfield);
            listfield.setChangeListener(selectServer);
            initializeList();
            reloadList();
        }
    
        private void reloadList()
        {
            listfield.setSize(list.size());
        }
    
        private void initializeList()
        {
            serverlist = new ServerList();
            for(int i = 0; i < serverlist.serverCount(); i++)
            {
                Server server = serverlist.printServers(i);
                list.addElement(server);
            }
        }
    
        public boolean onClose()
        {
            Connection.logout();
            close();
            return true;
        }
        //What I tried
        FieldChangeListener selectServer = new FieldChangeListener() {
            public void fieldChanged(Field field, int context) {
                int index = listfield.getSelectedIndex();
                Server server = (Server) callback.get(listfield, index);
                try {
                    Connection.UseServer(server.getid());
                } catch (ConnectionClosedException e) {
                    Dialog.alert("Connection closed");
                } catch (IOException e) {
                    Dialog.alert(e.getMessage());
                }
                main.ChangeScreen("ServerUser");
            }
        };
    
        private class ListCallback implements ListFieldCallback
        {
    
            public void drawListRow(ListField listfield, Graphics g, int index, int y, int w)
            {
                Server server = (Server) list.elementAt(index);
                String text = server.toString();
                if(server.isOnline())
                {
                    g.drawBitmap(new XYRect(0, 13, 15, 15), online, 0, 0);
                }
                else
                {
                    g.drawBitmap(new XYRect(0, 13, 15, 15), offline, 0, 0);
                }
                g.drawText(text, 20, y, 0, w);
            } 
    
            public Object get(ListField listField, int index) {
                return list.elementAt(index);
            }
    
            public int getPreferredWidth(ListField listField) {
                return getWidth();
            }
    
            public int indexOfList(ListField listField, String prefix, int start) {
                return list.indexOf(prefix, start);
            }
    
        }
    }
    

    I hope you can help me.

    Moochers

    Welcome on the support forums.

    I suggest that you crush navigationclick (and maybe keychar if you want to enter, return back... to do something).

    Please note that blocking operations, such as networking, must be executed on a separate thread. Do not put this code directly in the event handler.

  • Tunnel to establish an SSL connection inside a SSL connection

    I have an application that establishes a SSL30Connection with a web proxy server. This connection is opened using the ConnectionFactory. To enable HTTPS through proxy web, trying to create an SSL connection to a website (for example google.com) that uses the proxy server of SSL connection as its "subConnection" (see javadocs for SSL30Connection). When I try to do, I find myself with an EOFException or a ConnectionClosedException.

    I am aware of the workaround described here and have tried to use it, but still, the SSL connection to the remote server does not.

    Does anyone know if this kind of functionality is supported by the BB? Is there a 3rd party API that could achieve this?

    I open a topic in the RIM developer Issue Tracker as well:

    https://www.BlackBerry.com/jira/browse/JAVAAPI-2179

    Thank you.

    It turns out that several things went wrong.

    (1) the proxy has been close the connection after I read the response HTTP CONNECT. The fix for this consisted of two parts:

    ++ By adding a "Proxy-Connection: keep-alive" header.

    + Changing the way I read the answer. Before, I read the inputStream in 256 b pieces until Ihit-1. I changed it to simply read until I touched a line return character as the CONNECTION response is onlyone linelong.

    After you make these changes, I was able to make a socket: / / connection to the proxy and then do a ssl: / / to the remote server with the proxy as subConnection of ssl connection. However, when I tried to do a ssl: / / connection to the server, I always got the EOFException at the opening of the ssl: / / connection to the remote server. Then, like Santa himself immersed in to give me a Christmas gift at the beginning... I remembered that I had met problems with ssl: / / connections before; specifically, to write data to an ssl: / / OutputStream of connection REQUIRES a call to OutputStream.flush (). If you don't flush, data is never written (or the buffer is really big... anyway, adding that a function flush() suits). Remember this problem led me to the last part of the solution to this problem.

    (2) I wrapped the proxy ssl connection and its already open input and output stream in a class that looks like this:

    public class ProxyStreamConnectionWrapper implements StreamConnection {
    
        private StreamConnection stream;
        private DataInputStream inputStream;
        private DataOutputStream outputStream;
    
        public ProxyStreamConnectionWrapper(StreamConnection stream, DataInputStream dataInputStream, DataOutputStream dataOutputStream) {
    
            this.stream = stream;
            this.inputStream = dataInputStream;
            this.outputStream = dataOutputStream;
        }
    
        public DataInputStream openDataInputStream() throws IOException {
    
            return inputStream;
        }
    
        public InputStream openInputStream() throws IOException {
    
            return inputStream;
        }
    
        public void close() throws IOException {
    
            stream.close();
        }
    
        public DataOutputStream openDataOutputStream() throws IOException {
    
            return new DataOutputStream( openOutputStream() );
        }
    
        public OutputStream openOutputStream() throws IOException {
    
            return new OutputStream() {
    
                public void write( byte[] b, int off, int len ) throws IOException {
    
                    outputStream.write( b, off, len );
                    outputStream.flush();
                }
    
                public void write( byte[] b ) throws IOException {
    
                    outputStream.write( b );
                    outputStream.flush();
                }
    
                public void write( int b ) throws IOException {
    
                    outputStream.write( b );
                    outputStream.flush();
                }
            };
    }
    

    I got the idea of this wrapper from a previous post I already linked to above. The solution is in the openOutputStream() method. Adding the function flush() after each write the ssl handshake forces given the connection to the remote server ssl proxy server offline.

    Merry Christmas!

  • connection problems on BB 9500 Storm

    Hi, I got a new device right now-9500 Storm. I wrote a simple application that only connects to the server, like this:

    _sc = (SecureConnection) Connector.open ("ssl://addresstro;") deviceside = true");

    and I can not connect, all the times I had:

    Unable to connect net.rim.device.api.io.ConnectionClosedException: closed connection

     

    I put in appropriate under Advanced-> TCP options access point. The browser works. And the server is too late, cause using the same code that I can connect using different devices (8300/8800/8700...).

    I do not know the storm unit and I don't know if there is anything else that I need to activate the connections in my applications?

    I will be grateful for any suggestion,

    Kind regards

    Browsers on a BlackBerry could connect on a different course (not direct TCP).  You can try the httpdemo and/or socketdemo provided with the BlackBerry JDE?  Don't you see the same results with these applications?

  • Error reading Inputstream

    Error reading Inputstream
            
    -Online Exception net.rim.device.api.io.ConnectionClosedException error: closed stream
    Here is my code modual

      try
            {
                String url="http://maps.googleapis.com/maps/api/geocode/xml?latlng=21.175128,72.867236&sensor=false";
                String rawData =connectionData.getData();
    
                httpConn = (HttpConnection) Connector.open(url,Connector.READ_WRITE);
                int status = httpConn.getResponseCode();
                if(status==HttpConnection.HTTP_OK)
                {
                    InputStream is=httpConn.openInputStream();
                    if(is != null)
                    {
                        byte[] data = IOUtilities.streamToBytes(is);
                        result = new String(data, "UTF-8");
                        System.out.println("Result from Server:- "+result);
                        is.close();
                        httpConn.close();
                        onDataEnd();
                    }
                }
                //Close the connection.
                if(httpConn!=null)
                    httpConn.close();
            }
            catch (Exception e)
            {
                System.out.println("Exception "+e.toString());
            }
    

    as a higher code, I get this error "byte data [] = IOUtilities.streamToBytes (is);
    also I try other way to read feeds, but same error on appeal of webservices while for the other same service work very well
            
    and an unexpected thing is that when I put breackpoint on ' byte data [] = IOUtilities.streamToBytes (is);
    his response to migrate perfactly and read

    and when I put the next breakpoint, this isn't the line reach ther and gives me an error
            
    Help, please...!

    I understand the reasons to make checking the connection you make, but the code that you will lead

    (a) significant problems when you repeat the test, that you do not close the connections

    (b) delay processing while you connect to RIM, so every connection you make will take twice as long.

    Before considering further at your code I encourage you to withdraw this method completely and look rather using the ConnectionFactory to get your connection.  He's going to do pretty much the same job as your code, without fees.

  • HttpConnection errors

    Hi all

    I have a J2ME MIDlet that requires the use of the network through HttpConnection. The handset prompts me to allow or prohibit access to the network. I click Yes to allow access of netowork, the arrows at the top right of the screen show network activity, however, theMIDlet never theprogression intervenes and report a problem on the network. I know the network code works, as I have tested the MIDlet on other phones j2me and other emulators. Is there some sort of permissions that I need to activate or required additional signature?

    The exception returned is a ConnectionClosedException.

    I've actually narrowed it down. What was going on, it was the blackberry handsets didn't access the DataInputStream returned from the socket after the connection has been closed. All the other handsets don't care if the connection has been closed. Instead, I had to write in the DataInputStream DataInputStream another before the connection was closed so that I could access it later.

  • Unable to connect to the file

    Hello

    I have the following error when I want to open a connection to a file on the server.

    ConnectionClosedException: Not connected

    The code is:

    HttpConnection conn = null;
    
    String connSuffix = updateConnSuffix();
    this.url = this.url + connSuffix;
    
    conn = (HttpConnection) Connector.open(this.url, Connector.READ_WRITE, true);
    status = conn.getResponseCode();
    

    The cam of exception to the last line. My problem is that it works for an xml but not for an image. The URL is correct! I'm not what I can do!

    Maybe I should say that I work with 4.5 (!)

    Any ideas?

    Best regards

    Hello

    Thanks much for the ideas. I asked my admins and what they have is what they inexplicable server and now everything works fine! I didn't know what it was, but now I'm happy!

    Best regards

  • Connectivity problem

    Hi all

    I have a strange problem:

    My app connect successfully to a service, where it sends and receives a Json content. Writing and reading are successes in 2 independent threads that share the same connection. The amount of received data is averaged around 1 KB/sec. The data sent 20 bytes / 10 seconds - this acts as a keep-alive mechanism.

    What happens is that connection drops after 1 minute or so give me either "java.io.InterruptedIOException: Local connection has expired after ~ 120000 ', or 'net.rim.device.api.io.ConnectionClosedException '... But in this case only for BES/MDS, BIS and Wap2.0. Via direct TCP or Wi - Fi, all right...

    I am far from an expert MDS, but is there an extra handling for these modes of 3 connection?

    Kind regards

    Isabelle

    Get long after the problem was solved: it turns out that the physical connection was not closed... I'm just to catch this exception and do nothing else. Reading will be no subsequent deliveries data.

Maybe you are looking for