problem of InputStream

Hello

When I use IOUtilities... streamToBytes (.);

or

while((ch = inputStream.read()) != -1){

}

He both seem to be suspended...

IOUtilities does not seem to prevent the code to move to the next line.

inputStream.read () is not complete - 1 is found.

I uses direct TCP sockets.

I'm doing something wrong?

These two methods assume that the other end closes the connection, otherwise you will not get an eof (- 1).

I suspect my suggestion to use IOUtilities was a mistake.

During the processing of an outlet, you should probably read the next block of data, so you must have some sort of header that indicates the number of bytes coming, or another way to detect the end of the data block.

Tags: BlackBerry Developers

Similar Questions

  • InputStream in device throws exception SaxParser

    Hi all, I am working on OS 5.0.

    In my application, I have connected to the network using HttpConnection. I've added the necessary parameters to test the device. The connection sets up in the device, but it is throwing

    '& #x1f' SaxParser invalid character exception

    I don't know that that's the problem with InputStream, but not with the Httpconnection.

    a strange beviour, I've observed while debugging in the Simulator is... When I pass a URL with parameters make me same thing '& #x1f' bad character SaxParser exception, but if I pass the direct URL without setting the XML file is the analysis and works very well.

    any1 has faced previously this kind of problem? How to solve this problem?

    If the data from the server is compressed, then you will need to decompress before feeding it to the parser. If the data are encoded with gzip (uncompressed), try something like this:

    HttpConnectionFactory connFactory = new HttpConnectionFactory(_XMLUrl);connection = (HttpConnection)connFactory.getNextConnection();if (connection.getResponseCode() == HttpConnection.HTTP_OK) {    inputstream = new GZIPInputStream(connection.openInputStream());    parser.parse(new InputSource(inputstream));} else {    // error}
    

    If the server really uses zip compression, then you will need to use a ZlibInputStream. It is less likely, because the zip compression is oriented file, while gzip is aligned flow and more commonly used for responses from the server.

    A few other notes about your code:

    1. you don't need to create an InputStreamReader; the Analyzer can understand the encoding of the data of the (inflated) input stream itself.
    2. You must use connection.openInputStream () instead of connection.openDataInputStream (). Expect UTF-8 text, not Java data types, in the input stream.
    3. Definition of the Content-Type request property is not make sense unless you publish data to _XMLUrl (which, from your code, you do not).
    4. If the server powers up properly the response headers, you can check if the answer is gzip-ed using "gzip".equals (connection.getEncoding ()) after the call to connection.openInputStream (). " (My suggested code blindly guess gzip). Don't forget to check, however, that the process server is actually defining the header of the correct answer. many authors of server scripts don't know or are lazy about it. (If you control both sides, of course, you can safely be lazy.)
    5. In your second example in code, you should probably be defining the request text/xml HEADER_ACCEPT, instead of HEADER_ACCEPT_ENCODING property. Typical values for Accept-Encoding are 'gzip', 'compress' and 'identity', not ' text/xml '.
  • 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.

  • InputStream missing "\n\r".

    Hello

    I am writing an application that connects to my server via Http and receives in response Xml.

    The problem I faced is that even if the server sends a valid Xml code, I get no "\r\n" and it is causing me trouble.

    Does anyone have an idea, what the problem?

    Here is an example of code from my original code:

    InputStream inGetData = connection.openInputStream();
    int len = (int)connection.getLength();
    byte[] data = new byte[len];
    inConn.read(data, bytesread, len - bytesread);
    String dataStr = new String(data, "UTF-8");
    

    In addition, the method I use is GET and I put the following connection property, 'Accept ', ' * / * '.

    I tried it on your Nokia device and there is no problem, so I guess it's about BB.

    THX.

    Found the problem - server damaged Xml...

  • GZIP-problem for the Turkish language

    Hi all
    I am using gzip content-encoding and accept-encoding in properties. For the language Turkish gzip does not work very well it shows like EMC Akkua? Â?, HA? A¼seyin to? Â? random? A±A? Â? Kan. How to perform correctly.

    Thank you...

    Just saw your second message.

    I suspect that your problem is in unzipResponse - try this code instead.  Furthermore, I just wrote this, not compiled or tested, I hope you get the idea and can correct any errors you find.

    public String unzipResponse (io InputStream) throws Exception {}
    String returnString = "";
    try {}
    Gz GZIPInputStream = new GZIPInputStream (io);
    ubyte [] bytes = IOUtilities.streamToBytes (gz);
    returnString = new String(bytes,"UTF-8");
    }
    catch (Exception ex) {}
    Dialog.Alert ("unzipResponse:" + ex.getMessage ());
    }
    Return returnString;
    }

  • BrowserField encoding problem

    Hello! Please, help me! I spent almost all day, but have had no success. My BrouserField is showing '? ' characters instead of the non-English characters.
    I need to get the Ribbon XML, analyze and display in the BrowserFiled.
    I use these classes:

    (1) WaitScreen - PopupScreen from the example of knowledge base

    public class WaitScreen extends PopupScreen {
    
        private LabelField _ourLabelField = null;
    
        private WaitScreen(String text) {
            super(new HorizontalFieldManager());
            VerticalFieldManager _vfm = new VerticalFieldManager();
            _ourLabelField = new LabelField(text, Field.FIELD_HCENTER);
            _vfm.add(_ourLabelField);
            this.add(_vfm);
            this.setBackground(BackgroundFactory.createSolidTransparentBackground(Color.BLACK, 225));
        }
    
        public static void showScreenAndWait(final Runnable runThis, String text) {
            final WaitScreen thisScreen = new WaitScreen(text);
            Thread threadToRun = new Thread() {
                public void run() {
                    // First, Waintdisplay this screen
                    UiApplication.getUiApplication().invokeLater(new Runnable() {
                        public void run() {
                            UiApplication.getUiApplication().pushScreen(thisScreen);
                        }
                    });
                    // Now run the code that must be executed in the Background
                    try {
                        runThis.run();
                    } catch (Throwable t) {
                        t.printStackTrace();
                        throw new RuntimeException("Exception detected while waiting: " + t.toString());
                    }
                    // Now dismiss this screen
                    UiApplication.getUiApplication().invokeLater(new Runnable() {
                        public void run() {
                            UiApplication.getUiApplication().popScreen(thisScreen);
                        }
                    });
                }
            };
            threadToRun.start();
        }
    }
    

    (2) RSSHandler - class auxiliary for analysis

    public class RSSHandler extends DefaultHandler {
        boolean isItem = false;
    
        boolean isTitle = false;
        boolean isLink = false;
        boolean isDescription = false;
        boolean isPubDate = false;
        boolean isGuid = false;
    
        public String[] title = new String[] {};
        public String[] link = new String[] {};
        public String[] description = new String[] {};
        public String[] pubDate = new String[] {};
        public String[] guid = new String[] {};
        String value = "";
    
        public void startElement(String uri, String localName, String name,
                Attributes attributes) throws SAXException {
            if (!isItem) {
                if (name.equalsIgnoreCase("item"))
                    isItem = true;
            } else {
                if (name.equalsIgnoreCase("title"))
                    isTitle = true;
                if (name.equalsIgnoreCase("link"))
                    isLink = true;
                if (name.equalsIgnoreCase("description"))
                    isDescription = true;
                if (name.equalsIgnoreCase("pubDate"))
                    isPubDate = true;
                if (name.equalsIgnoreCase("guid"))
                    isGuid = true;
            }
        }
    
        public void characters(char[] ch, int start, int length)
                throws SAXException {
            if (isTitle || isLink || isDescription || isPubDate || isGuid)
                value = value.concat(new String(ch, start, length));
        }
    
        public void endElement(String uri, String localName, String name)
                throws SAXException {
            if (isItem && name.equalsIgnoreCase("item"))
                isItem = false;
            if (isTitle && name.equalsIgnoreCase("title")) {
                isTitle = false;
                Arrays.add(title, value);
                value = "";
            }
            if (isLink && name.equalsIgnoreCase("link")) {
                isLink = false;
                Arrays.add(link, value);
                value = "";
            }
            if (isDescription && name.equalsIgnoreCase("description")) {
                isDescription = false;
                Arrays.add(description, value);
                value = "";
            }
            if (isPubDate && name.equalsIgnoreCase("pubDate")) {
                isPubDate = false;
                Arrays.add(pubDate, value);
                value = "";
            }
            if (isGuid && name.equalsIgnoreCase("guid")) {
                isGuid = false;
                Arrays.add(guid, value);
                value = "";
            }
        }
    }
    

    (3) CaptionScreen (screen with BrowserField I need to show the result of the XML parsing)

    public class CaptionScreen extends MyMainScreen
    {
        private BrowserField _browserField;
    
        public CaptionScreen(Application app, String section)
        {
             //....
             GetArticles getArticles = new GetArticles("http://" + _urlWithArticles, _browserField);
             WaitScreen.showScreenAndWait(getArticles, "LOADING");
        }
    
        static class GetArticles implements Runnable {
            String _url = null;
            BrowserField _resultBrowser;
    
            public GetArticles(String urlToGet, BrowserField resultBrowser) {
                this._url = urlToGet;
                this._resultBrowser = resultBrowser;
            }
    
            public void run() {
                // Try to download new articles and parse the answer
                HttpConnection httpConn = null;
                InputStream is = null;
                RSSHandler rssHandler = new RSSHandler();
    
                try {
                    httpConn = GetConnection(_url);
    
                    is = httpConn.openInputStream();
                    try {
                        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
                        parser.parse(is, rssHandler);
                    }
                    catch (ParserConfigurationException e) {
                        e.printStackTrace();
                    }
                    catch (SAXException e) {
                        e.printStackTrace();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (IOException ioe) {
                } catch (Exception e) {
                } finally {
                    try {
                        if ( httpConn != null ) {
                            httpConn.close();
                        }
                    } catch (Exception e) {
                    }
                    httpConn = null;
                }
    
                final String htmlArticles = generateHtml(rssHandler);
                UiApplication.getUiApplication().invokeLater(new Runnable() {
                    public void run() {
                        _resultBrowser.displayContent(htmlArticles, "");
                    }
                });
            }        
    
            // Method for html generation to showing in BrowserField
            private String generateHtml(RSSHandler rssHandler) {
                String result = "";
                if(rssHandler == null) {
                    return result;
                }
                result += "News";
    
                for(int i = 0; i < rssHandler.title.length; i++) {
                    result += rssHandler.title[i] + "
    " + "LINK
    " + rssHandler.description[i] + " "; } result += ""; return result; } private HttpConnection GetConnection(String _url) throws IOException { if (DeviceInfo.isSimulator()) { _url = _url + ";deviceSide=true"; } MyConnFact _myConnFact = new MyConnFact(); HttpConnection _httpConn = null; ConnectionDescriptor _connDesc = _myConnFact.getConnection(_url); if (_connDesc != null) { _httpConn = (HttpConnection)_connDesc.getConnection(); } return _httpConn; } } }

    It works very well (showing WaitScreeen, data download), but all characters not English shows as '?'
    I found a few discussions with the same problem (especially this one)

    http://supportforums.BlackBerry.com/T5/Java-development/how-to-show-other-languages-in-BrowserField/...

    and this one

    http://supportforums.BlackBerry.com/T5/Java-development/BrowserField-can-not-display-UTF-8-character...

    but I don't understand, how and where do I I implemented HttpConnection in my code.
    Please, give me advice or tell, how I change my code to solve this problem?

  • Strange connection problem

    This happens on the Simulator and the current device.  I did it on 8800, 8703e, 8320 and 7100i.  OS 4.1 and 4.2.  Also tried on multiple media.  Tried with and without a BES.

    I am able to create an http connection initially, and everything works fine.  I log in, I get my data.  Large.

    However, when I leave my application and go to the Blackberry Desktop and turn the Wi - Fi market then re - enter my app and try to make the same connection, it will not work.

    When you run the debugger, it seems to try and make the ' status int = httpConn.getResponseCode (); »

    line of code and won't go further.  It will be expire.  In fact, he gets caught by the try catch statement.  The Exception toString is ' java.io.InterruptedIOException: Local connection timed out after ~ 120000'

    My connection code is...

         StreamConnection s = null;      String finalUrl = "";       finalUrl = "http://" + login.url + directoryPath + filename + local.getUrlPlus();       try {           s = (StreamConnection) Connector.open(finalUrl);            HttpConnection httpConn = (HttpConnection) s;           httpConn.setRequestMethod(HttpConnection.POST);         httpConn.setRequestProperty("user-agent", "BB DOC");            httpConn.setRequestProperty("content-type", "application/x-www-form-urlencoded");           httpConn.setRequestProperty("connection", "close");         byte d[] = data.getBytes();         httpConn.setRequestProperty("content-length", Integer.toString(d.length));          OutputStream os = s.openOutputStream();         os.write(d);            if (os != null)             os.close();         int status = httpConn.getResponseCode();            if (status == HttpConnection.HTTP_OK) {             InputStream input = s.openInputStream();                //parses the content returned               input.close();          } else {                ;//Had a server connection problem                      }           s.close();          httpConn.close();       } catch (IOException e) {                   ;//Catches the timeout here.        }
    

    Seems the only way to solve this problem is to restart the Simulator.

    Only occurs when the wireless is displayed/hidden market.  Sound like something not be reset or something.  I have simulated this when the unit is made of coverage and brought back in coverage, but the error never occurred.  Only when the wireless is turned on and the.

    What of even weirder, is that I have been using the same connection code for over a year without any problems.

    Someone at - he already experienced this?  Its driving me crazy.

    Any help would be more then appreciated.  Thank you!

    This seems to be a matter of BlackBerry Simulator.  I was able to reproduce and checked that it has been fixed in version 4.3.0 the BlackBerry Simulator.

  • Convert InputStream into byte array

    Hey everybody,

    I really need help with this problem that I can not get rid! I am doing an application that loads an image saved on the BB device and sends it to a server, the problem is we can send only a byte [].

    So I try to apply the following method:

    -Loading the image via the FileConnection class

    -Open an InputStream from the FileConnection said

    -Convert an array of bytes as InputStream

    The code should look like this I guess:

    FileConnection file = (FileConnection) Connector.open ("Original_SealV.jpg");
    InputStream is = file.openInputStream ();

    Byte [] img = null;
    int temp = is.read ();
    {while(Temp>0)}

    Convert bytes here?

    }

    This is the last step I'm missing, I tried several methods, but could not run, so I beg for a bit of the collective wisdom of these forums...

    Could someone help me? I will not forget the congratulations!

    or you can always use the standard API

    Byte [] buf = IOUtilities.streamToBytes (stream);

  • Problems with GZip &amp; FTP

    Hello

    in my application, I need to send a file compressed using ftp.

    To do this, I used a class initially write to use with J2SE (SimpleFTP)

    I have change for use with RIM API and it work with file bit compressed (like 4 KB) but when I try to send one just a little big (12Ko) I have a problem to decompress: gzip - me to say end of file unexpected.

    It is a bit of cod used:

    //In a thread i create the connection and change to BIN
    ftp.connect(ip, port, user, psw, true, apn, apnUser, apnPsw);
    ftp.cwd(dir);
    ftp.bin();
    
    //here I obtain a csv representation of my object and store it in a //String var
    String csv = r.toCSV();
    
    //this method ask to ftp object to store a ByteArray in the file named //file and i want to zip it and return true if all is ok
    if (ftp.stor(new ByteArrayInputStream(csv.getBytes("UTF-8")),file,true))
    //...do things
    

    the method of object ftp stor have this code:

    /**
     * Sends a file to be stored on the FTP server. Returns true if the file
     * transfer was successful. The file is sent in passive mode to avoid NAT or
     * firewall problems at the client end.
     */
    public synchronized boolean stor(InputStream inputStream, String filename, boolean zipped) throws IOException {
    
        sendLine("PASV");
        String response = readLine();
        if (!response.startsWith("227 ")) {
            throw new IOException("SimpleFTP could not request passive mode: " + response);
        }
        String ip = null;
        int port = -1;
        int opening = response.indexOf('(');
        int closing = response.indexOf(')', opening + 1);
        if (closing > 0) {
            String dataLink = response.substring(opening + 1, closing);
            String[] tokenizer = Functions.splitString(dataLink, ',', -1);
            try {
                ip = tokenizer[0] + "." + tokenizer[1] + "." + tokenizer[2] + "." + tokenizer[3];
                port = Integer.parseInt(tokenizer[4]) * 256 + Integer.parseInt(tokenizer[5]);
            } catch (Exception e) {
                throw new IOException("SimpleFTP received bad data link information: " + response);
            }
        }
        String url = "socket://" + ip + ":" + port + urlParam;
        Logger.log(this, "Try to open passive connection to "+url);
        SocketConnection dataSocket = (SocketConnection) Connector.open(url);
        dataSocket.setSocketOption(SocketConnection.LINGER, 5);
        dataSocket.setSocketOption(SocketConnection.DELAY, 5);
    
        sendLine("STOR " + filename);
    
        response = readLine();
        if (!response.startsWith("125 ")&&!response.startsWith("150 ")) {
            dataSocket.close();
            dataSocket=null;
            throw new IOException("SimpleFTP was not allowed to send the file: " + response);
        }
        Logger.log(this, "Connected to "+url);
    
        OutputStream output;
        if (zipped)
            output = new GZIPOutputStream(dataSocket.openOutputStream(),GZIPOutputStream.COMPRESSION_BEST);
        else
            output = dataSocket.openOutputStream();
    
        byte[] buffer = new byte[512];
        int bytesRead = 0;
    
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
    
        output.flush();
        output.close();
        output = null;
        dataSocket.close();
        dataSocket=null;
    
        response = readLine();
        return response.startsWith("226 ");
    }
    

    The readline() and sendline("") methods read or write to the ftp decision-making, a line ended with CR and I so need to send FTP commands

    I think that everything is ok, for this problem I find in a forum that the problem will be the use of ASCII in FTP method, but I change to BIN

    Any idea?

    Thank you in advance!

    Hello

    Finally, I solved the problem.

    I find the solution in the documentation GZIPOutputStream

    You must pass OutputStream to GZIPOutputStream, zipping it and then you must close GZIPOutputStream but you must use the original OutputStream.

    So in my SimpleFTP class I have to write about gzip, close it then flush() and close() the original outputstream.

    Knit

    I had the new method of stor() here to see

    /**
         * Sends a file to be stored on the FTP server. Returns true if the file
         * transfer was successful. The file is sent in passive mode to avoid NAT or
         * firewall problems at the client end.
         */
        public synchronized boolean stor(InputStream inputStream, String filename, boolean zipped) throws IOException {
    
            sendLine("PASV");
            String response = readLine();
            if (!response.startsWith("227 ")) {
                throw new IOException("SimpleFTP could not request passive mode: " + response);
            }
    
            String ip = null;
            int port = -1;
            int opening = response.indexOf('(');
            int closing = response.indexOf(')', opening + 1);
            if (closing > 0) {
                String dataLink = response.substring(opening + 1, closing);
                String[] tokenizer = Functions.splitString(dataLink, ',', -1);
                try {
                    ip = tokenizer[0] + "." + tokenizer[1] + "." + tokenizer[2] + "." + tokenizer[3];
                    port = Integer.parseInt(tokenizer[4]) * 256 + Integer.parseInt(tokenizer[5]);
                } catch (Exception e) {
                    throw new IOException("SimpleFTP received bad data link information: " + response);
                }
            }
            String url = "socket://" + ip + ":" + port + urlParam;
            Logger.log(this, "Try to open passive connection to "+url);
            SocketConnection dataSocket = (SocketConnection) Connector.open(url);
            dataSocket.setSocketOption(SocketConnection.LINGER, 5);
            dataSocket.setSocketOption(SocketConnection.DELAY, 5);
    
            sendLine("STOR " + filename);
    
            response = readLine();
            if (!response.startsWith("125 ")&&!response.startsWith("150 ")) {
                dataSocket.close();
                dataSocket=null;
                throw new IOException("SimpleFTP was not allowed to send the file: " + response);
            }
            Logger.log(this, "Connected to "+url);
    
            OutputStream output = dataSocket.openOutputStream();
            byte[] buffer = new byte[512];
            int bytesRead = 0;
    
            if (zipped){
                GZIPOutputStream zipOutput = new GZIPOutputStream(output,6, GZIPOutputStream.MAX_LOG2_WINDOW_LENGTH);;
                while (!isAskForAbort() && (bytesRead = inputStream.read(buffer)) != -1) {
                    zipOutput.write(buffer, 0, bytesRead);
                }
                zipOutput.close();
            } else {
                while (!isAskForAbort() && (bytesRead = inputStream.read(buffer)) != -1) {
                    output.write(buffer, 0, bytesRead);
                }
            }
            if (isAskForAbort()){
                abor();
                output.close();
                output = null;
                dataSocket.close();
                dataSocket=null;
                try {
                    setAskForAbort(false);
                } catch (BbException e) {/*nothing to do. Here ftp is conected*/}
                return false;
            }
            output.flush();
            output.close();
            output = null;
            dataSocket.close();
            dataSocket=null;
    
            response = readLine();
            return response.startsWith("226 ");
        }
    

    Thank you much for the help.

  • Problem: How to upload files to server

    I'm a newbie to BB development. I have problems to download the file from my BB to the server.

    Any help would be appreciated... Thank you...

    Code of the thread:

    class UploadThrd extends Thread
    {
    Limit string = "*";
    String lineend = "\r\n";
    String twoHyphens = "-";
    int maxBufferSize = 0;
    DataInputStream fileInputStream = null;
    public void run()
    {
    try {}
    FileConnection fis=(FileConnection)Connector.open("file:///store/home/user/newfile.txt");
    CreateFileScreen.showMsg ("recovered file name");
    InputStream inputStream = fis.openInputStream ();

    ByteArrayOutputStream Bos = new ByteArrayOutputStream();
    int buffersize = (int) fis.fileSize ();
    ubyte [] buffer = new byte [buffersize];
    int length = 0;
    While ((length = InputStream.Read (buffer))! = - 1).
    {
    Bos.Write (buffer, 0, Length);
    }
    Byte [] b = bos.toByteArray ();
    CreateFileScreen.showMsg ("copied file...");

    ConnectionFactory connFact = new ConnectionFactory();
    ConnectionDescriptor connDesc;
    connDesc = connFact.getConnection ("http://www.myserver.net/z/upload.php");
    If (connDesc! = null)
    {
    HttpConnection conn;
    Conn = (HttpConnection) connDesc.getConnection ();
    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run() {}
    Dialog.Alert ("http connected...");
    }
    });
    conn.setRequestMethod (HttpConnection.POST);
    conn.setRequestProperty ("Content-Type", "multipart/form-data; limit = "" + limit); "
    conn.setRequestProperty ("login", "Keep-Alive");
    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run() {}
    Dialog.Alert ("' HTTPConnection TOGETHER... verification response Code.. '");
    }
    });
    conn.setRequestProperty ("Content-Length", Long.toString (b.length));
    end of series

    If (conn.getResponseCode () == HttpConnection.HTTP_OK)
    {
    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run() {}
    Dialog.Alert ("response Code: HTTP_OK!");
    }
    });
    OutputStream os = conn.openOutputStream ();
    Write bytes
    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run() {}
    Dialog.Alert ("written bytes..");
    }
    });

    String CT = "Content-Type: multipart/form-data;" limit = "+ limit;"
    OS. Write ("Content-Disposition: form-data;") Name =-"source\" "." GetBytes());
    OS. Write (LineEnd.GetBytes ());
    OS. Write (LineEnd.GetBytes ());
    OS. Write ("BlackBerry". GetBytes());
    OS. Write (LineEnd.GetBytes ());

    OS. Write (twoHyphens.GetBytes ());
    OS. Write (Boundary.GetBytes ());
    OS. Write (LineEnd.GetBytes ());

    String filename = "z\newfile.txt; »
    OS. Write ("Content-Disposition: form-data;") name =-"Filedata\"; filename =------"". GetBytes());
    OS. Write (FileName.GetBytes ());
    OS. Write("\"".) GetBytes());
    OS. Write (LineEnd.GetBytes ());

    OS. Write (CT. GetBytes());
    OS. Write (LineEnd.GetBytes ());
    OS. Write (LineEnd.GetBytes ());

    OS. Write (b, 0, b.length);

    OS. Write (LineEnd.GetBytes ());

    OS. Write (twoHyphens.GetBytes ());
    OS. Write (Boundary.GetBytes ());
    OS. Write (twoHyphens.GetBytes ());
    OS. Write (LineEnd.GetBytes ());
    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run() {}
    Dialog.Alert ("downloaded file!");
    }
    });
    OS. Flush();
    OS. Close();
    }
    on the other
    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run() {}
    Dialog.Alert ("no connection");
    }
    });
    Conn.Close ();
    }

    }
    catch (Exception e) {}
    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run() {}
    Dialog.Alert("===exception!");
    }
    });
    }
    }
    }

    Class app:

    SerializableAttribute public class CreateFileApp extends UiApplication
    {
    /**
    * Entry point for application
    @param args command-line arguments (not used)
    */
    Public Shared Sub main (String [] args)
    {
    Try
    {
    FileConnection fc = (FileConnection)Connector.open("file:///store/home/user/newfile.txt");
    If (! fc.exists ())
    {
    FC. Create(); create the file if it doesn't exist
    }
    OutputStream outStream = fc.openOutputStream ();
    outStream.write ("happy test".getBytes ());
    outStream.close ();
    FC. Close();
    CreateFileScreen.showMsg ("I'll upload file..");
    Thread UploadThrd = new UploadThrd();
    thread. Start();
    }
    catch (IOException e)
    {
    System.out.println ("= IOException:"+ e.getMessage () ");
    }
    catch (Exception e1)
    {
    System.out.println ("= Exception:"+ e1.getMessage () ");
    }
    Create a new instance of the application and make the currently
    who runs the thread of the application of the event dispatch thread.
    PAP CreateFileApp = new CreateFileApp();
    theApp.enterEventDispatcher ();
    }

    /**
    * Creates a new CreateFileApp object
    */
    public CreateFileApp()
    {
    Push a screen onto the stack in the user interface for rendering.
    pushScreen (CreateFileScreen.cfs);
    }
    }

    The screen class:

    / public final class CreateFileScreen extends screen
    {
    /**
    * Creates a new CreateFileScreen object
    */
    public static CreateFileScreen SFC = new CreateFileScreen();
    public CreateFileScreen()
    {
    Set the displayed title of the screen
    setTitle ("create a file");
    }
    public static void showMsg (String msg)
    {
    LabelField lbl = new LabelField (msg);
    CFS. Add (LBL);
    }
    }

    Hello, welcome to the Forums!

    You must use the property tto line allow multi part download on your BB using Post server.

    It is a good example in nokia Forums, where you can fashion it accordint to your settings & file Type.

    http://www.developer.Nokia.com/community/wiki/HTTP_Post_multipart_file_upload_in_Java_ME

    Thank you

  • Problems with Connector.open

    I'm having a problem with the re-login to a HttpsConnection once a failure has occurred. I send a message to a php site that works 100% OK. However, if I drop the receipt when sending at the reception is retrieved Connector.open no reconnect not (even after a long wait). and gives a "java.io.InterruptedIOException: connection Local has expired" exception. The issue is not corrected until the phone is rebooted.

    I use MDS to transport and endpoint certificate has a valid certificate (does not Self-signed). Before I drop the front desk, a message is sent correctly and using the console creates the following log entries:

    [0,0] * start sending:

    [0,0] SSL :-> CH

    [0,0] SSL:<>

    [0,0] SSL:<>

    [0,0] SSL:<>

    [0,0] SSL:<>

    [0,0] SSL :-> CKE

    [0,0] SSL :-> CCS

    [0,0] TLS :-> F

    [0,0] TLS:<>

    [0,0] VMISVt = 0, h = 1a7b, id = d15a33128dfbb5d9

    [0,0] VM:LNTDa = validation, t = 1, p = D8Mobile

    [0,0] * open Stream:

    [0,0] * sending data:

    [0,0] * server response: 200

    [0,0] * Flushing bos

    [0,0] * input stream of Flushing

    [0,0] * Flushing DOUT

    [0,0] * Flushing HC

    [0,0] TLS:<-Alert -="" level="1" description="">

    [0,0] * emptied all

    Once the reception has been abandoned and valued, the connection begins to open the SSL session and shows the following:

    [0,0] * start sending:

    [0,0] SSL :-> CH

    He gets Nevers to: SSL [0,0]:<>

    After the time-out period, it then returns the exception

    IO exception: java.io.InterruptedIOException: Local connection timed out after ~ 15000

    [0,0] * Flushing bos

    [0,0] * emptied all

    Of course the connection is instantiated is no longer so I can't even try his end on the connector at this stage. I also see the following in the MDS newspapers - although I'm not sure its related:

    <2012-01-18 10:42:03.921="" gmt="">:[528]:::

    What follows is a version of my code. All this code runs since a thread to work constantly in the loop.

    HttpsConnection hc =null;

    InputStream is =null;

    Dout OutputStream =null;

    ByteArrayOutputStream Bos =newByteArrayOutputStream();

    byte [] res = null;

    VR;

    {

    System.

    HC = (HttpsConnection) Connector.open (url + ";" ConnectionTimeout = 15000; deviceside = false');

    "Credentials of string = this._username +": "+this._password;"

    byte [] encodedAuthorization = Base64OutputStream.encode (credentials.getBytes (), 0, credentials.length (),false,false);

    () hc.setRequestProperty

    "Authorization", "basic" +newString (encodedAuthorization));

    () hc.setRequestProperty

    'Content-Type', ' multipart/form-data; Boundary = "+ getBoundaryString());

    dout = hc.openOutputStream ();

    dout. Write (postBytes);

    dout. Flush();

    this._responseCode = hc.getResponseCode ();

    dout. Close();

    is = hc.openInputStream ();

    int ch;

    while ((ch = is.read (())! = - 1).

    {

    Bos.Write (ch);

    }

    RES = bos.toByteArray ();

    }

    catch (IOException ioe) {

    System.out.println ("* IO Exception:" + ioe.toString ());

    this._responseCode = 0;

    RES = null;

    }

    catch (Exception e)

    {

    System.out.println ("* send the Message of the Exception:" + try ());

    this._responseCode = 0;

    RES = null;

    }

    Finally

    {

    VR;

    {

    if (bos! = null) {

    Bos.Close ();

    }

    if (is! = null) {

    is. Close();

    }

    if (dout! = null) {

    dout. Close();

    }

    if (hc! = null) {

    HC. Close();

    }

    }

    catch (Exception e2)

    {

    System.out.println ("* Message send Exception 2:" + e2.toString ());

    }

    }

    of return ;

    }

    I tried on 8700,8900 and 9700 device simulators. I am running JRE 5.0.0 and MDS v4.1.4

    Any help or suggestions will be appreciate - I spent nearly a week debugging it and its slowly driving me crazy!

    Thank you

    Andy

    Try to use the factory connections if you are targettin devices in 5.0 or above, it might solve the prob.

  • Socket RAW InputStream.availalble () in stream wireless network always 0?

    For all BlackBerry networking expert out there.

    The explanation of the problem will be quite long, so I'll try to structure the message to facilitate navigation.

    Introduction

    Recently, we went from HttpConnection to raw sockets in our application.  It wasn't an easy decision (a lot of extra code had to be written and debugged) - it stemmed from the fact that on different devices HttpConnection behaves very differently and sometimes we would just hang out here for always trying to read something, although enough bytes was available in the buffers of the system (I have seen it with my own eyes; can develop if anyone is interested).  There are other reasons, but this has been the main.

    Previously working solution

    Once we went to the outlets and implemented our own HttpConnection (not me - someone to increase their knowledge in networks of BB did this), our problems have disappeared. In order to reduce the chance of getting stuck forever, we check InputStream.available () of the socket and, if there is always a thread. Sleep() 0, for some small interval (makes me cringe, but well, the user makes a call blocking!) then read just one byte (hoping that there might be something).  It worked for all trackball/touchcpad devices and all kinds of connections (SDM is a separate issue, but we managed)...

    New problem

    ... until we have tested the Storm (5.0 Storm1 and Storm2 - both 5.0 behaved similarly) with all, but connections WiFi disabled.  We have connected WiFi router to the company (I then repeated the test at home with my wireless router and got the same results).  BB browser worked fine.  However, our code began fails on our internal waiting time.  When I connected the phone to the debugger and set up breakpoints, I quickly discovered that InputStream.available () always zero returns! I'm not kidding!

    Our code was constantly diverted waiting, waiting, reading another byte, read a byte...  Even when I changed the way that we on the download time was exceptionally slow (as in "unbearable").

    Worse still - when I tried to wait before making the first longer interval (100ms) read, followed by reading the characters one by one without waiting, the phone started rebooting randomly!

    Request

    Someone has seen something similar?  If so, what was your approach?  I won't sit idly while waiting the answers here - I have a few ideas to try-, but if anyone has been there, it would be nice if you can just push me in the right direction.

    Thanks in advance,

    Arkady.

    Other people have had problems with available().  I'm surprised that you managed to get that you have to be honest, I thought he always returned 0.

    We make socket connections, and always the transmission with a header field that contains prefix length.  So read on the Blackberry is basically

    (a) header to read

    (b) reading of data

    (c) to process the data

    (d) proceed to (a).

    Another user and I had problems recently with http and OS 5.0 using WiFi connections - circuit up to and/or time out when reading the response.  This is the thread

    http://supportforums.BlackBerry.com/T5/Java-development/network-IO-hang-on-OS5/m-p/541487

    I would recommend you change your implementation of socket and detection of data along these kinds of lines, in other words, how data should be read and set up some kind of detection/stall.

    Does make sense?

  • Problem downloading and saving a file text not in the SD card

    Hi all

    My goal is to download a KML file and save it to the SD card.

    My code did not throw any error and has also created a new file in the SD card. But the data inside is not correct.

    Someone please correct my mistake.

    Here is my code:

    public final class MyTest_ToDownloadAndSave extends {screen

    public MyTest_ToDownloadAndSave() throws IOException

    {

    StreamConnection conn = null;

    InputStream inputStream = null;

    FileConnection fConn = null;

    OutputStream outputStream = null;

    byte [] byteVal;

    StringBuffer sb = new StringBuffer();

    try {

    Conn is Connector.open (StreamConnection) ("https://sites.google.com/site/mykmltest1/multilockml/cta.kml", Connector.READ_WRITE);.

    inputStream = conn.openInputStream ();

    int ch;

    while ((ch = inputStream.read ())! = - 1).

    {

    SB. Append ((char) ch);

    }

    }catch(IOException e) {}

    throw new IOException ("problem with the URL");

    } {finally

    try {

    if (inputStream! = null ) {

    inputStream.close ();

    }

    if (conn! = null ) {

    Conn.Close ();

    }

    }catch(System.Exception e) {}

    throw new IOException ("close connections problem");

    }

    }

    "Rtx RichTextField = new RichTextField (downloaded successfully"+ sb.toString ());

    Add (RTX);

    try {

    fConn = (FileConnection)Connector.open("file:///SDCard/BlackBerry/cta2.kml",Connector.READ_WRITE);

    if (! fConn.exists ()) {

    fConn.create ();

    }

    outputStream = fConn.openOutputStream ();

    if (sb! =null & sb.toString ()! = "") {

    byteVal = new byte[sb.length ()];

    byteVal = sb.toString () .getBytes ();

    outputStream.write (byteVal);

    }

    RichTextField rtx1 is new RichTextField ("registered successfully");.

    Add (rtx1);

    }catch(IOException e) {}

    throw new IOException ("writing to SD card problem");

    } {finally

    try {

    if (outputStream! = null ) {

    outputStream.close ();

    }

    if (fConn! = null ) {

    fConn.close ();

    }

    }catch(System.Exception e) {}

    throw new IOException ("close connections problem");

    }

    }

    }

    }

     

    http://en.Wikipedia.org/wiki/List_of_HTTP_status_codes

    3xx is the guy you want

  • problem using the FileConnection API (JSR 75) in an application for Blackberry "BOLD" MIDLET

    Hello

    I developed a MIDLET which is to read files and store the contents of files in arrays. I could make using the FileConnection API in J2ME (Java ME) and it works very well in mobile emulators provided by Sun, Sun Kit tool 2.5.1 wireless and Sprint Wireless tool 3.3.2 Kit. I have been using netbeans IDE 6.8 for this.

    Now, here's the deal. Playback of the files does not work when in one of the Blackberry mobile emulators. I tried to install all versions of Blackberry JDE 4.2.1 to 5.0 and test the same thing, but none of them worked.  After reading that the Blackberry plugin for Eclipse is good, I used it to find that I am always faced with the problem.

    I desperately need help. Can someone help me do the reading work file in a Blackberry emulator? I insert the code that makes the file reading. It reads a file containing a single column of 60 entries, and stores it in an array of double type.

    Vector time = new Vector();
    
    try{
    
     FileConnection filecon = (FileConnection) Connector.open("file:///" +"SDCard/BlackBerry/documents/"+"timescale.dat");
    
     if(!filecon.exists()) {    Dialog.show("Note ! ", "File doesn't exists !", "okay","cancel"); }
    
         StringBuffer sb = new StringBuffer();      try      {       InputStream in = filecon.openInputStream();       int chars;
    
           while ((chars = in.read()) != -1)// read until EOF is reached       {          if(chars == '\n') // read all characters until the end of line is reached          {              time.addElement(sb.toString().trim()); // stores all the characters as a vector element when the end of line is reached
    
                  sb.delete(0,sb.length());// clear the stringbuffer for storing the next line of the file
    
              }
    
              else          {              sb.append((char)chars); // appends each character read          }
    
          }// end of while
    
        }    catch(IOException e)    {               }
    
        filecon.close();
    
    }// end of outer try
    
       int i =0;   Enumeration etime = time.elements();
    
       while(etime.hasMoreElements() && i < 60) // timescale.dat has 60 entries in one column   {       time_1d[i]=Double.parseDouble(etime.nextElement().toString());// convert to double       i++;   }
    

    Can you elaborate on what does not work?  Is an error or exception thrown?  If Yes, what is it and what line of code triggers it?

    You have configured the BlackBerry smartphone Simulator to simulate a micro SD card?

    Use a computer filesystem in the form of microSD card

    http://supportforums.BlackBerry.com/T5/testing-and-deployment/use-a-computer-file-system-as-a-microS...

  • 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.

Maybe you are looking for