Problem on httpconnection

I need get the XML from the server, and I use httpconnection.  Even I use the simple code. It may also not work. What is the problem

Show the code below:

SerializableAttribute public class XMLTestScreen extends form {}

public XMLTestScreen() {}

setTitle ("HttpConnection Demo");

try {}

HttpConnection coon = (HttpConnection) connector

.the ("http://www.google.com.sg");

Int State = coon.getResponseCode ();

If (status == HttpConnection.HTTP_OK) {}

Dialog.Alert ("Get");

Add (new LabelField ("get"));

} else {}

Dialog.Alert ("Nothing");

Add (new LabelField ("Nothing"));

}

} catch (Exception e) {}

e.printStackTrace ();

}

}

}

Unfortunately to understand any code provided to you, you're gong to have to do an apprenticeship.  RexDoug suggested a number of places, let me suggest a bit more.

The developer's Guide is a very good read, you can pick it up for 4.6 here.

http://docs.BlackBerry.com/en/developers/deliverables/3802/development.PDF

This has a chapter entitled: "Creating connections" inside is a promising section called «... data recovery» "sounds just like what you want.

To save the search, the sticky thread that RexDoug suggested is here:

http://supportforums.BlackBerry.com/Rim/Board/message?board.ID=java_dev&thread.ID=29103

You will also find a free sample around code that did something like what you want, including this one:

http://developerlife.com/tutorials/?p=884

Tags: BlackBerry Developers

Similar Questions

  • Problem with HttpConnection when it connects only not to wifi - java.io.IOException: Tunnel failed

    Hi all

    I develop an application that communicates with a database MySQL via PHP stored on the server scripts. Until today I've developed using the Simulator, and everything has been fine. I now started to test on a device and, while being connected to wifi, everything is still fine. However, the minute I turn off wifi and let the network provider, O2 UK, I get:

    "Request failed: reason: java.io.IOException: Tunnel failed".

    The source of the connection code is as follows:

       public void run() {
           // The following code will only build under JDE 4.5 and later
    
           try {
               String connectionParameters = "";
               // JDE 4.3 is required to get WLANInfo
               if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
                   // Connected to a WiFi access point
                   connectionParameters = ";interface=wifi";
               } else {
                   int coverageStatus = CoverageInfo.getCoverageStatus();
                   ServiceRecord record = getWAP2ServiceRecord();
                   if (record != null
                           // In JDE 4.5 CoverageInfo changed the name of
    COVERAGE_CARRIER to COVERAGE_DIRECT
                           // The constant value for both is the same,
    '1', so you can use that to avoid any
                           // dependency on JDE 4.5
                           && (coverageStatus & CoverageInfo.COVERAGE_DIRECT) ==
                           CoverageInfo.COVERAGE_DIRECT) {
                       // Have network coverage and a WAP 2.0 service book record
                       connectionParameters = ";deviceside=true;ConnectionUID="
                               + record.getUid();
                   } else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) ==
                           CoverageInfo.COVERAGE_MDS) {
                       // Have an MDS service book and network coverage
                       connectionParameters = ";deviceside=false";
                   } else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) ==
                           CoverageInfo.COVERAGE_DIRECT) {
                       // Have network coverage but no WAP 2.0 service book record
                       connectionParameters = ";deviceside=true";
                   }
               }
    
               // Pop up a dialog showing the parameters chosen
               UiApplication.getUiApplication().invokeLater(
                       new DialogRunner("Connection Params: "
                               + connectionParameters));
    
               HttpConnection connection = (HttpConnection) Connector.open(url
                       + connectionParameters);
    
               connection.setRequestMethod(method);
               if (method.equals("POST") && postData != null) {
                   connection.setRequestProperty("Content-type",
                           "application/x-www-form-urlencoded");
                   OutputStream requestOutput = connection.openOutputStream();
                   requestOutput.write(postData);
                   requestOutput.close();
               }
               int responseCode = connection.getResponseCode();
               if (connection instanceof HttpsConnection) {
                   HttpsConnection secureConnection = (HttpsConnection) connection;
                   String issuer = secureConnection.getSecurityInfo()
                           .getServerCertificate().getIssuer();
                   UiApplication.getUiApplication().invokeLater(new
    DialogRunner("Secure Connection! Certificate issued by: " + issuer));
    
               }
               // Really you should check for more than just HTTP_OK
               if (responseCode != HttpConnection.HTTP_OK) {
                   screen.requestFailed("Unexpected response code: "
                           + responseCode);
                   connection.close();
                   return;
               }
    
               String contentType = connection.getHeaderField("Content-type");
               ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
               InputStream responseData = connection.openInputStream();
               byte[] buffer = new byte[10000];
               int bytesRead = responseData.read(buffer);
               while (bytesRead > 0) {
                   baos.write(buffer, 0, bytesRead);
                   bytesRead = responseData.read(buffer);
               }
               baos.close();
               connection.close();
    
               screen.requestSucceeded(baos.toByteArray(), contentType);
           } catch (IOException ex) {
               screen.requestFailed(ex.toString());
           }
       }
    

    I scoured these forums and tried everything I can find. I tried different settings, including changing the APN settings both wap and mobile options for O2. Nothing seems to solve this problem.

    Any help would be appreciated!

    Thank you

    Jack

    OK, good news. Fixed. Thanks a lot for your answers. I would have understood the connection settings as they appear to have been the problem.

    I don't remember exactly which it generated, but I decided to try replacing it with the generator of connectionParameter above with the snippet connSuffix here:
    http://supportforums.BlackBerry.com/T5/Java-development/connecting-your-BlackBerry-http-and-socket-c...

    Worked like a dream, so I'm very indebted to all those who contributed to this. It now seems to work little matter the type of connection is available including BES.

    In case anyone is interested, however, I tried all combinations of settings APN bloody O2, but it came to nothing. I am disappointed that it was the connection settings I developed that a book by Apress, and I followed this particular part, Word for Word.

    Thank you all for the world of useful information here!

  • Problem with HTTPConnection

    Hello

    I have an app balckberry making an HTTP request and download a JSON object, it works perfectly in all simulators and devices ' "BOLD", Bold2 (5.0), curve, I have two camera a storm 2 (5.0) and a (5.0) 9630 tour where I get the following error message.

    I prefer IOUtilities.streamToBytes (), the approach that you use, which looks like it might have a strong overload.

    It also gives me the ability to decode the octets using UTF-8, that your approach does not.  And it is perhaps part of the problem.  If the server sends UTF-8 and you read it in the way you did, then you could interpret some characters.

  • Problems of HttpConnection

    Hi all

    I have an application that is out on the market for a bit it works fine. In the last two days, the httpconnections were incredibly slow and wedging on. no code has changed! Is there something to do with the servers?

    I just added '; deviceside = true' and it worked!... why it worked before with her?

  • Http connection problem

    Hello

    I have some problems with httpconnection. I have to make 2 connections, first to retrieve data from a web service. The second is used to play audio data stream.

    Here's what I do:

    First of all, I call a web service using a httpconnection (this works well):

    HttpConnection httpConn = (HttpConnection)Connector.open(sLocator, Connector.READ);InputStream is = oHttpConn.openInputStream();byte[] loadedContent = IOUtilities.streamToBytes(is);ByteArrayInputStream bytestream = new ByteArrayInputStream(loadedContent);
    
    // Some work with the bytestream
    
    is.close();httpConn.close();
    

    Later in the code, I do in a separate thread:

    HttpConnection httpConn =(HttpConnection)Connector.open(sLocator);
    InputStream is = httpConn.openInputStream();
    
    player = Manager.createPlayer(is, "audio/mpeg");                                                           player.realize();
    player.prefetch();
    player.start();
    

    My problem is that this second httpconnection only works if I'm not the first one before (the web service call) (actually only when I comment the web service call the player does his job).

    Am I missing something?

    I'm working on a simulator at the moment (with SDM launched), I didn't add the parameter "deviceside" to my URL.

    However if I join '; deviceside = true' for the second connection, it works sometimes, but only if I use it in the first connection.

    Can you help me?

    Thank you

    Franck

    Hello

    Are you running the connection of two in the same thread? If this isn't the case, I make sure that the first thread of the connection was closed successfully without exception.

    Also, you must add the transport protocols to your all URLS.

    I have the same situation when I make two API calls where the 2nd call API is based on the outcome of the first and I do it in the same thread of connection and it works fine.

  • Open accessory secure binding

    Hello

    I'm setting up a search for blackberry client application.  It made a post when you hit search and retrieves the XML that I use to display information on the search screen. So far so good. This is what my XML looks like:

           Word Attachment                http://dv-localhost/test.nsf/0/1F8B7C7116EC84838525764200520B4E/$file/Suggestions.doc    
    

    I am able to do it without problem using HttpConnection. My next challenge is to display the attachment from the link that is in the xml code, ""<>> "it is a full path to the attachment, attachment." I've tried doing the attachmentlink as a hyper link found on this link How to display a hyperlink. When I tried to open the attachment directly from the link, I get an error on the blackberry screen saying "HTTP ERROR 500: internal server error." an unexpected condition has occurred, preventing your request to be fulfilled, this can be caused by a problem with the gateway...'.» When I click on ok, then the message is "address family not supported by protocol family: connect". Is it possible to open this supported attached directly from a link, is - parts. How can I recover this attachment is there a quick way to display the attachment from the link. Any help would be appreciated.

    Thank you.

    -DV

    What model of smartphone BlackBerry and the version of the software BlackBerry device test you on?  You can find this under Options, all on the BlackBerry Smartphone.  You can manually open the same URL use the BlackBerry browser?

  • Blackberry problems with javax.microedition.HttpConnection

    Hi all

    I am currently working on an application that connects to the Web service using javax.microedition.io.HttpConnection;

    I want to do several generations for the request of 4.7, 5.0 and 6.0. I have a very big problem because as I've debugged since now the request to the server is only to send the version 4.7 and I have not found a solution to work for other versions. The code is the same, but I have an InterruptedIOException with the message that LocalConnection expired after ~ 10000. I had this error on the 9800 Simulator tests.

    How it is possible to work on 4.7 but on other versions of crash?

    Have you had similar problems? Shoud I code to help with this? This is a very critical situation.

    Kind regards

    Bogdan

    Try to use '; deviceside = true' to your URL. Also, take a look at Peter in sticky for many useful code to develop applications of HttpConnection.

  • Httpconnection BlackBerry problem

    HttpConnection works not when I try to connect through wap2. I am adding the connection string 'ConnectinUID = wap2 trans' at the end of the url, but connection works as an alternative. Can any one help in this issue?

    Problem solved by adding the field header "Connection: close".

  • HttpConnection IOException Tunnel has no problem

    Hello

    I wrote a code that use HTTPConnection to call a url:

    HttpConnection conn = (HttpConnection) Connector.open)

    «http:// *.» ***. : 5556/mobileservice.asmx; deviceside = true; ConnectionTimeout ="+ timeOut, Connector.READ_WRITE, true);

    And I got the IOException:Tunnel Failed on 9000 "BOLD" and the 8900. (So far, I had only to test on both devices).

    I think I had put the apn correctly. So I don't understand the reason for this exception.

    Can someone give me help?

    Thanks in advance

    Sorry, my mistake. I used the wrong NPC. I use .com but not .nl.

    And it works now.

    Thanks for your help

  • HELP Needed HttpConnection PROBLEM

    Hi I'm a Newbie to the Blackberry development... I'm trying to read data from the URL through HttpConnection. Here it is my code. When I call through Simulator code, the following code does not run... System.out.println ("MDS getResponseCode" + c.getResponseCode ()); There is no exception too... Pls help what's wrong in my code...

    Thanks in advance - Poy

    import java.io.IOException;
    import java.io.InputStream;
    java.lang.String import;
    Import javax.microedition.io.Connector;
    Import javax.microedition.io.HttpConnection;
    Import net.rim.device.api.ui.Field;
    Import net.rim.device.api.ui.FieldChangeListener;
    Import net.rim.device.api.ui.UiApplication;
    Import net.rim.device.api.ui.component.ButtonField;
    Import net.rim.device.api.ui.component.LabelField;
    Import net.rim.device.api.ui.container.MainScreen;

    Main class
    SerializableAttribute public class HttpCxn extends UiApplication {}

    Starting point
    Public Shared Sub main (String [] args) {}
    HttpCxn httpCxn = new HttpCxn();
    httpCxn.enterEventDispatcher ();
    }

    Initial screen of calls
    public HttpCxn() {}
    pushScreen (new HttpCxnScreen());
    }

    }

    class HttpCxnScreen extends form {}

    Declare my initial variables

    ButtonField submitButton = new ButtonField ("Submit", ButtonField.CONSUME_CLICK);
    HttpCxnScreen screen = this;

    Main screen, including the entries for the character/server names
    public HttpCxnScreen() {}

    Create the label of title for the main screen
    LabelField mainTitle = new LabelField ("HTTP CONNECTION", LabelField.ELLIPSIS
    | LabelField.USE_ALL_WIDTH);
    Set title to the top of the label
    setTitle (mainTitle);
    Add other elements to the form

    Add (submitButton);

    Create the feature of the "submit" button
    submitButton.setChangeListener (new FieldChangeListener() {}

    ' Public Sub fieldChanged (field field, int context) {}
    Thread postnameThread = new Thread (new ServerConnection());
    postnameThread.start ();
    }

    });

    }

    http connection class
    ServerConnection class extends Thread {}

    String url = ""http://172.24.30.27: 9091/demo/index.jsp;deviceside=false ";"

    Method called by the Send button
    public ServerConnection() {}
    System.out.println ("test");
    }

    public void run() {}
    C HttpConnection = null;
    InputStream is = null;
    Response string;
    int rc;

    try {}
    StringBuffer buffer = new StringBuffer();
    System.out.println ("URL" + URL);
    c = (HttpConnection) Connector.open (url);
    System.out.println ("AZtest" + c); My debugger not crossed this line
    Get the response code is open the connection,
    Send the request and read HTTP response headers.
    The headers are stored until asked.
    System.out.println ("MDS getResponseCode" + c.getResponseCode ());
    RC = c.getResponseCode ();
    System.out.println ("CHECK MDS" + rc);
    If (rc! = HttpConnection.HTTP_OK) {}
    System.out.println ("HTTP_OK" + RC);
    throw new IOException ("HTTP response code:" + rc);
    }

    is = c.openInputStream ();

    Get the ContentType
    The string of type = c.getType ();

    The length and process data
    int len = (int) c.getLength ();
    If (len > 0) {}
    real int = 0;
    int BytesRead = 0;
    data Byte [] = new ubyte [len];
    While ((bytesread! = len) & (real! = - 1)) {}
    real = is.read (data, bytesread, len - bytesread);
    bytesRead += real;
    }
    } else {}

    int ch;

    While ((ch = is.read (())! = - 1) {}
    ch = is.read ();
    buffer. Append ((Char) ch);
    }
    response = buffer.toString ();

    }
    } catch (Exception e) {}

    e.printStackTrace ();

    }
    }
    }
    }

    This message can help.

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

  • How to manage the HttpConnection to do:

    Hello

    Well, my problem is that I am a httpconnection by blackberry to a tomcat server apache where I have a servlet that establish a connection to a database, I want the blackberry to show me if the connection is successful or not. I have the blackberry to show me the message if was successful or not. This is the code.

    Method that connect to servlet:

    ' public void IniciarSesion (String pLog, String pPass) throws IOException
    {
    String url = "http://localhost: 8081/ConexServ/sv_Conectar";
    OutputStream os = null;
    Try
    {

    HttpConnection hc = (HttpConnection) Connector.open (url);

    hc.setRequestMethod (HttpConnection.POST);

    hc.setRequestProperty ("User-Agent", "' profile/MIDP-2. 0 Configuration/CLDC - 1.0" ");
    hc.setRequestProperty("Content-Language","es-ES");

    OS = hc.openOutputStream ();
    OS. Write (("Log_="_+_pLog).getBytes ());
    OS. Write ((«_&_pass_=_"+_pPass).getBytes ());
    OS. Flush();
                
    HC. Get
    }
    catch (ClassCastException e)
    {
    throw new IllegalArgumentException ("not a HTTP URL");
    Dialog.Inform ("error" + e.getMessage ());
    }
    Finally
    {
    If (OS! = null)
    OS. Close();
    }
    }

    -------------------------------------------------------------------------------------------------------------------------------------

    It's the method that receive the settings in the servlet:

    protected void processRequest (HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, SQLException
    {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter ();
    Journal of the string, pass;
    ConexionBD Conex.
    Try
    {
    GB = Globales.getInstance ();
    Journal = request.getParameter("Log").toString ();
    pass = request.getParameter("Pass").toString ();
    This brand of method the conexion returns true or false

    F. IniciarSesion(log,pass,out);
    }
    Finally
    {
    out. Close();
    }
    }

    Please give on how to do what I want,

    Give the NetworkAPIDemo a glance. This is a very good example on how should be HTTP connections.

    If you are using the eclipse IDE go to file > import > import of samples BlackBerry

    In the new window make sure you click "Clear all" (as I'm sure you don't want to look at ALL the examples right now). Head down to the NetworkAPIDemo to complete the import.

    Samples are a GREAT way to reach 90% of the common tasks that you will implement. It has been my single most important resource.

    You can also see this post: http://supportforums.blackberry.com/t5/Java-Development/Sample-HTTP-Connection-code-and-BIS-B-Access...

    Finally, be sure to use the search feature before asking questions (I know I'm guilty of not doing that from time to time). HttpConnections have been covered ad nauseam.

  • Prob HttpConnection BlackBerry running in the Simulator

    I want to call a url and get the response of the url of my Blackberry App data. For this, I use HttpConnection. Here is the code I use:

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

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

    SerializableAttribute public class TestApp extends UiApplication {}

    private screen _mainScreen;

    private static TestApp _app.

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

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

    _mainScreen.Add (testField);

    pushScreen (_mainScreen);

    C HttpConnection = null;
    DataInputStream tell = null;

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

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

    try {}
    If (say! = null)
    tell. Close();
    If (c! = null)
    c.Close ();
    } catch (IOException e) {}
    e.printStackTrace ();
    }
    {} catch (NullPointerException e)
    e.printStackTrace ();
    }
    }

    }

    Public Shared Sub main (String [] args) {}
    _APP = new TestApp();
    _APP.enterEventDispatcher ();

    }
    }

    When I try to run the code in the Simulator, I get ' 0 ', then ' 1' and after that, after much time "no trace of the stack" doesn't appear in the debug window, and as soon as the text makes its appearance, level with the text app becomes visible in the Simulator screen. There is no problem in the internet connection in the Simulator, I set up the Wi - Fi and I tested it I open any Web site in the browser. What is the problem in my code?

    You must start MDS

    MDS is service or bridge to connect to internet for simulater

    install MDS and run it solve

    Download now

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

Maybe you are looking for

  • Can I cancel my action, "Restore Defaults"?

    My internet was very slow and not in normal display mode.Wrongly, I opted to restore the default settings and lost my Contacts.Can I restore everything?

  • lost all Contacts information

    I have synced my iCloud and a new iPadAir account an iPhone 4. Contact data on the iPhone disappeared. No idea how to get it back?

  • Question about rom 9900, override the method object failed

    Before I update the ROM (9900jAllLang_PBr7.1.0_rel2435_PL5.1.0.622_A7.1.0.862_AT_T.exe) for my 9900, I can easily overrides the method of object to change text styles or field label, for example the size of the font, color of the text and so on. But,

  • HP pavilion dv-7-6c95dx: hp pavilion dv - 7 laptop PC

    I have upgraded to Windows 10 and it has worked fine until today. Now, my hp Pavilion dv-7-6c95dx lights up briefly, have a click, then turns off. I did a hard reset by removing the battery, unpluging the power, dwon pluging in holding start for 30 s

  • Catalyst Control Center does not work after update win8.1

    My computer model mobile no is 017tx - Hp pavillion 15th,after update of victory 8 to win 8.1, Catalyst Control Center does not work. So I'm unable to move from the graphics options.