HttpConnection errors

Hi all

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

The exception returned is a ConnectionClosedException.

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

Tags: BlackBerry Developers

Similar Questions

  • ADF Mobile Client: Error when trying to import javax.microedition. *.

    Hello

    JDev throws errors at compile time when I try to deploy a sample Client Mobile ADF application.
    These errors are related to the import of javax.microedition.io. *.

    Error (11,29): javax.microedition.io package does not exist
    Error (12,29): javax.microedition.io package does not exist
    Error (180,9): could not find class HttpConnection
    Error (191,27): cannot find class HttpConnection
    Error (191,42): cannot find variable connector
    Error (250,49): inconvertible types
    Error (303,40): cannot find variable HttpConnection

    Guidance on the way in which these errors could be solved?

    Is there a wireless JDev extension to be installed to fix these errors related to J2ME?

    For JDev 10 g, I could find such an extension called JWE here: http://www.oracle.com/technology/products/iaswe/archive/developer/index.html
    I couldn't find any similar extension for JDeveloper 11.1.3.

    Kind regards
    Prasad.

    Hi, I just want to assure you - have you installed the ADF MObile Client extension yet? Visit JDev-Help-Check for updates official Oracle Extensions and updates and find the Extension of Oracle ADF MObile Client in the list. Check it out, download it and then restart JDev. It seems that the extension is not installed, is not able to load J2ME libraries.

    If you downloaded the extension already, please go to properties-libraries and classpath of the project and then see if the sample application makes reference to third party libraries, for example something RIM. If so, please check the path to the library.

    Once you have installed the extension, you can also access the customer Mobile ADF Developer's guide - it contains all the documentation around what you need to install first. Please take a look and see what you install - at the very least, you need to install BlackBerry JDE if you want to deploy for BlackBerry and Windows Mobile Emulator, if you want to test the application on Windows Mobile. Finally, if you need to synchronize the data, then you must also install Oracle Database Server Lite for MObile.

    Thank you

    Joe Huang

  • sending request giving 401 unauthorized error in Twitter

    Hi am using the following code to update my status in twitter, but gives a 401 unauthorized error

    can any one help on this... its urgency.

    Thank you

    cordially yakubpasha

    Sub update (String username, String password, string status) throws IOException {}
    String response = null;
    HttpConnection connection = null;

    /*
    * ask a String upadte my status
    */
    String query = "status =" + urlEncode (status);
    String length = String.valueOf (query.length ());
            

    /*

    * username and password code here
    */

    String userPass = username + ":" + password;
    Byte [] encrypted = Base64OutputStream.encode (userPass.getBytes (), 0,
    userPass.length (), false, false);
    String url = "https://twitter.com/statuses/update.xml";
                 
    try {}
    Connection = (HttpConnection) Connector.Open (URL);
    connection.setRequestMethod (HttpConnection.POST);
    connection.setRequestProperty ("User-Agent", "profile/MIDP-2. ("0 configuration/CLDC - 1.0");
    connection.setRequestProperty ("Content-Type", "application/x-www-formulaires-urlencoded");
    connection.setRequestProperty ("authorization", "Basic" + new String (encoded));
    connection.setRequestProperty("Content-Length",length);
                
    //
    connection.setRequestProperty ("Content-Length", len);
    OutputStream os = connection.openOutputStream ();
    OS. Write (u.GetBytes ());
    Dialog.Alert ("" + Connection.getResponseCode () + Connection.getResponseMessage ());
    If (connection.getResponseCode () == HttpConnection.HTTP_OK) {}
    StringBuffer buffer = new StringBuffer();
    InputStream is = connection.openInputStream ();
    int c;
                    
    ("Connection") Dialog.Alert;
    While ((c = is.read (())! = - 1) {}
                        
    buffer. Append ((Char) c);
                        
    }
    is. Close();
    response = buffer.toString ();
    Dialog.Alert (Response);
    }
    } catch (Exception ex) {}
    Dialog.Alert ("error message");
    System.out.println ("sdcfsdfsdfs" + ex.getMessage ());
    } {Finally
    If (connection! = null) {}
    try {Connection.Close ;}
    catch (IOException ext) {}
    }
    }
    }

    Hey I made with her...

    If any want to post a status lets you next...

    its works perfectly

    Sub update (String username, String password, string status)
    throws IOException {}
    String response = null;
    HttpConnection connection = null;

    String query = "status =" + urlEncode (status);
    String length = String.valueOf (query.length ());

    String userPass = username + ":" + password;
    Byte [] credentialsBytes = (username + ":" + password) .getBytes ();
    Byte [] encodedBytes = Base64OutputStream.encode (credentialsBytes, 0,)
    userPass.length (), false, false);
    String credentialString = new String (encodedBytes);

    String url = "https://twitter.com/statuses/update.xml";
        
    try {}
    connection = (HttpConnection), Connector.open (url);
    connection.setRequestMethod (HttpConnection.POST);

    connection.setRequestProperty ("Content-Type",
    "application/x-www-formulaires-urlencoded");
    connection.setRequestProperty ("authorization", "Basic"
    (+ credentialString);
    connection.setRequestProperty ("Content-Length", length);
    DataOutputStream out = new DataOutputStream (connection
    (. openDataOutputStream());
    out. Write (Query.GetBytes ());
    out. Flush();
    out. Close();
    If (connection.getResponseCode () == HttpConnection.HTTP_OK) {}
    StringBuffer buffer = new StringBuffer();
    InputStream is = connection.openInputStream ();
    int c;

    ("Connection") Dialog.Alert;
    While ((c = is.read (())! = - 1) {}

    buffer. Append ((Char) c);

    }
    is. Close();
    response = buffer.toString ();
    Dialog.Alert (Response);
    }
    } catch (Exception ex) {}
    Dialog.Alert ("error message");
    System.out.println ("sdcfsdfsdfs" + ex.getMessage ());
    } {Finally
    If (connection! = null) {}
    try {}
    Connection.Close;
    } catch (IOException ext) {}
    }
    }
    }
    }

    This code I copied from somewere am thanking him for sharing this code snippet
    public static String urlEncode(String s) {}
    If (s! = null) {}
    try {}
    s = String (new s.getBytes("UTF-8"), 'ISO-8859-1');
    } catch (UnsupportedEncodingException e) {}
    }
    StringBuffer tmp = new StringBuffer();
    try {}
    for (int i = 0; i)< s.length();="" i++)="">
    int b = (int) s.charAt (i);
    If ((b > = 0 x 30 && b <= 0x39)="" ||="" (b="">= 0 x 41 && b))<=>
    || (b > = 0x61 & b)<= 0x7a))="">
    tmp. Append ((Char) b);
    } Else if (b == 0x20) {}
    tmp. Append("+");
    } else {}
    tmp. Append ("%");
    If (b<= 0xf)="">
    tmp. Append ("0");
    }
    tmp. Append (Integer.toHexString ((b));
    }
    }
    } catch (Exception e) {}
    }
    Return tmp.toString ();
    }
    Returns a null value.
    }

  • Error! : duplicate definition for 'org.kxml2.io.KXmlParser '.

    Hi all

    Below I have attached my code using KSoap2.

    The following error message get up when I run the project.

    ".. \lib\kxml2-min-2.3.0.jar(org/kxml2/IO/KXmlParser.class): error! ': duplicate definition for 'org.kxml2.io.KXmlParser', in: org.kxml2.io.KXmlParser.

    I looked in the forums of BB, but I can't solve this problem...

    Please tell me hoe to solve this problem

    package mypackage;
    
    import java.io.InputStream;
    import java.io.OutputStream;
    
    import javax.microedition.io.Connector;
    import javax.microedition.io.HttpConnection;
    
    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.kxml2.io.KXmlParser;
    import org.xmlpull.v1.XmlPullParser;
    
    import net.rim.device.api.compress.GZIPOutputStream;
    import net.rim.device.api.system.CoverageInfo;
    import net.rim.device.api.system.WLANInfo;
    import net.rim.device.api.ui.Field;
    import net.rim.device.api.ui.FieldChangeListener;
    import net.rim.device.api.ui.component.ButtonField;
    import net.rim.device.api.ui.component.Dialog;
    import net.rim.device.api.ui.container.MainScreen;
    
    /**
     * A class extending the MainScreen class, which provides default standard
     * behavior for BlackBerry GUI applications.
     */
    public final class MyScreen extends MainScreen
    {
        /**
         * Creates a new MyScreen object
         */
        public MyScreen()
        {
            // Set the displayed title of the screen
            setTitle("MyTitle");
            ButtonField bf = new ButtonField();
            add(bf);
            BenoListener benoListener = new BenoListener();
            bf.setChangeListener(benoListener);
        }
    
        public class BenoListener implements FieldChangeListener {
            public void fieldChanged(Field field, int context) {
                try {
                    String serviceNamespace = "http://www.google.com/Services/google/";
                    String soapAction = "http://www.google.com/Services/google/Login";
                    String methodName= "Login";
                    String result = "";
                    String begin = ""
                            + "http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                            + "";
                    String end = "" + "";
                    String soapBody =begin;
                    soapBody += "http://www.google.com/Services/google\">";
                    soapBody += "";
                    soapBody += "[email protected]";
                    soapBody += "";
                    soapBody += "";
                    soapBody += "12345678";
                    soapBody += "";
                    soapBody += "";
                    soapBody += end;
                    SoapObject rpc = new SoapObject(serviceNamespace, methodName);
                    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                    envelope.encodingStyle = SoapSerializationEnvelope.ENC;
                    HttpConnection connection = (HttpConnection) Connector.open("https://services.google.com:8443/axis2/services/api/V1.0/GoogleServices"+ getConnectionParameter(),Connector.READ_WRITE);
                    connection.setRequestProperty("SOAPAction", soapAction);
                    connection.setRequestProperty("Content-Type", "application/x-gzip");
                    connection.setRequestProperty("Content-Encoding", "gzip");
                    connection.setRequestProperty("Accept-Encoding", "gzip");
                    connection.setRequestProperty("Content-Length","" + soapBody.getBytes().length);
                    connection.setRequestProperty("User-Agent", "kSOAP/2.0");
                    connection.setRequestMethod(HttpConnection.POST);
                    OutputStream os = connection.openOutputStream();
    
                    zipRequest(os, soapBody);
    //              os.write(soapBody.getBytes(), 0, soapBody.getBytes().length);
    //              os.close();
                    soapBody = null;
                    InputStream is = connection.openInputStream();
                    XmlPullParser xp = new KXmlParser();
                    xp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                    xp.setInput (is, null);
                    envelope.parse(xp);
                    result = (envelope.getResponse()).toString();
                    Dialog.alert("Result---"+result);
                } catch (Exception ex) {
                }
    
            }
    
            private String getConnectionParameter() {
                String connectionParameter = "";
                if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
                    connectionParameter = ";interface=wifi";
                } else {
                    int coverageStatus = CoverageInfo.getCoverageStatus();
                    if ((coverageStatus & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
                        connectionParameter = ";deviceside=false";
                    } else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
                        connectionParameter = ";deviceside=true";
                    }
                }
                return connectionParameter;
            }
    
                public void zipRequest(OutputStream io, String data) throws Exception{
                    try{
                        GZIPOutputStream gz = new GZIPOutputStream(io);
                        byte[] bytes = data.getBytes("UTF-8");
                        gz.write(bytes, 0, bytes.length);
                        gz.close();
                    }
                    catch(Exception ex){
                    }
            }
    
    }
    }
    

    I solved this problem of "Preverify" jar

  • HTTP - Error 502 gateway connection

    Hello

    In an application I'm developing with java and SDK v. 7.0.0, I am trying to connect via http to a server that is located on a private network. The code is pretty basic:

    String url = ""http://site.bl.company.net/login.asp;deviceside=true "; "
    ConFactory ConnectionFactory = null;
    try {}
    conFactory = new ConnectionFactory();
    conFactory.setTimeLimit (1000);
    HttpConnection conn = null;
    Conn = conFactory.getConnection (url) .getConnection () (HttpConnection);
    conn.setRequestMethod (HttpConnection.GET);
    conn.setRequestProperty ("Content-Type", "application/x-www-formulaires-urlencoded");
    RCODE int;
    RCODE = conn.getResponseCode ();
    If (rcode! = 200)
    {
    Error ("failed server to ' + this.urlStr + 'code HTTP' + String.valueOf (rcode));
    }
    }
    catch (Throwable t)
    {
    Error ("connection error:"+ t.getMessage () ');
    return;
    }

    The url is visible inside the company VPN. Phones, when the 3G, through BES to reach the VPN. If I type the url in the browser application when, the 3G, it can very well be reached. However, the app in 3G, the connection fails with code 502 (gateway error). We looked through newspapers and it seems that the request does not reach BES; where it might be failing?

    The connection works perfectly fine when the phone is connected in wifi on an access point in the VPN. It works very well to other URLS not on VPN under 3G and wifi.

    Any help/advice/suggestions/questions would be greatly appreciated!

    Thank you.

    If you run in a BES environment, and want to access something that's within the corporate network, you must use the suffix

    « ; deviceside = false '.

    otherwise, you are gong through the gateway to mobile operators, who of course has no access to the internal network.

    See here for more information:

    http://supportforums.BlackBerry.com/T5/Java-development/different-ways-to-make-an-HTTP-or-socket-con...

    But there is a curve ball here.

    Once an application has attempted to access a network located outside the corporate network (like you did with ";) deviceside = true'), that the request is normally prohibited access URL within the network.  It is the problem of split-pipe.  The idea is that if an application could open connections inside and outside of the firewall, it could copy the data from the corporate network to the outside.  It is so restricted.

    So, if you change your current application to use '; deviceside = false ' and then try on a business device that already has had your application under running with. " deviceside = true', it will probably fail the problem of split pipe.

    To work around this, you have three options:

    (a) wipe the device and reinstall the OS and application

    (b) to obtain your BES administrator to allow the app to access both inside and outside

    (c) create a new application.

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

  • The device push service get error 403

    Hello

    Here I am with push service problem * once again. I'm developing a push application. I have a problem in the recording of the pressure of the client App. I'm currently testing a Javelin and still get error HTTP 403 (refused). I would like to know what the problem is. What is my code or my device?

        private static final String URL = "http://pushapi.eval.blackberry.com/mss/PD_subReg?";
        private String PushServiceRegister(String parameter)
        {
        int responseCode = 200;
        String registrationUrl;
    
            try
            {
                registrationUrl = URL + "serviceid=" + CommBookApplication._serviceId;
                registrationUrl += "&osversion=" + DeviceInfo.getSoftwareVersion();
                registrationUrl += "&model=" + DeviceInfo.getDeviceName();
    
                // output:
                // http://pushapi.eval.blackberry.com/mss/PD_subReg?serviceid=xxx-eeR53M4h55eM02i5&osversion=4.6.1.92&m...
    
                if(parameter != null && parameter.length() > 0)
                {
                registrationUrl += "&" + parameter;
                }
    
                HttpConnection connection = (HttpConnection) Connector.open(registrationUrl);
                connection.setRequestMethod("GET");
    
                responseCode = connection.getResponseCode();
                if(responseCode != HttpConnection.HTTP_OK)
                {
                    // Always go here with response code = 403
                    connection.close();
                    return String.valueOf(responseCode);
                }
                else
                {
            // Process response data using output stream
                }
            }
            catch (IOException exception)
            {
                // Handle exception
            }
    
        }
    

    AAH, finally got it.

    Add '; deviceside = false; "ConnectionType = mds-*" at the end of the URL.

    find the * replacement in the BPSS client side code

    (* This is a little strange, it's like I'm talking in this thread )

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

  • State HTTP 500 when I get a webpage with HTTPConnection

    Hello

    I have a method that get a string containing the HTML of a Web page source code. I use HTTPConnection utils for this. This method works perfectly, I've used this for another project, and I didn t have a problem. In my new project I want to use this method again on a specific Web page (I can´t say the URL of this web site).

    My problem is that this page returns a 'HTTP 500 status' error. If I use the BlackBerry browser, web load too perfectly and in the BB Simulator.

    I thought that the problem is the HTTP request header, and I've included a few properties of the request as:

    httpConnection.setRequestProperty ("Content-Type", rawInputContentType);

    Connection","keep-alive");
    httpConnection.setRequestProperty ("User-Agent", Mozilla/5.0 (BlackBerry"; U; BlackBerry 9360; ES) AppleWebKit / 534.11 + (KHTML, like Gecko) Version/7.1.0.190 Mobile Safari / 534.11 + ");"
    httpConnection.setRequestProperty ("accept", "text/html,application/xhtml+xml,application/xml,*/*;q=0.5");
    httpConnection.setRequestProperty ("Accept-Language", "es");
    httpConnection.setRequestProperty ("Accept-Encoding","gzip, deflate");
    httpConnection.setRequestProperty ("x-wap-profile","------"http://www.blackberry.net/go/mobile/profiles/uaprof/9360_80211g/7.1.0.rdf\ "" "");

    But the error is the same. The exception is:

    org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.RuntimeException: de.arvatomobile.bdev.scr.exception.MissingDeviceDetectionHeaderExceptionorg.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:681)org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)javax.servlet.http.HttpServlet.service(HttpServlet.java:617)javax.servlet.http.HttpServlet.service(HttpServlet.java:717)info.magnolia.cms.filters.MgnlMainFilter.doFilter(MgnlMainFilter.java:108)info.magnolia.cms.filters.MgnlMainFilter.doFilter(MgnlMainFilter.java:216)com.mondiamedia.shop.magnolia.filter.MagnoliaContextFilter.doFilter(MagnoliaContextFilter.java:113)info.magnolia.cms.filters.AbstractMgnlFilter.doFilter(AbstractMgnlFilter.java:88)org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)com.mondiamedia.common.filter.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:83)com.mondiamedia.shop.vodafone.es.adult.filter.BlacklistFilter.forwardToBlacklist(BlacklistFilter.java:221)com.mondiamedia.shop.vodafone.es.adult.filter.BlacklistFilter.doFilter(BlacklistFilter.java:99)org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    

    Do you know why I get this error? Thank you.

    It s resolved. He had two problems. First of all, I am connected with the WIFI of my office, and it was very bad signal. The second, it was only necessary to specify the user-agent, other parameters of header gave problems.

  • Error 401 on Twitter device

    Hi I Don t know why my fall of code on 9700 OS 5, I try in OS6 9300, 9780 OS 6 and all devices with 0 7 s and the same code work as expected.

    I take this forum code, I don´t remenber where and to change some lines and constant.

    all devices of returned code 200 but 9700 give me a 401

    Help, please

    public static String requestToken(){
            String url = Const.REQUEST_TOKEN_URL;
            String header = oauth_header(url, HttpProtocolConstants.HTTP_METHOD_GET);
            String requestTokenUrl = concatURL(url, header);
            System.out.println(requestTokenUrl);
            HttpsConnection connection = null;
            InputStream input = null;
            try{
                connection = (HttpsConnection) HttpUtils.getConfiguredConectionFactory().getConnection(requestTokenUrl).getConnection();
                connection.setRequestMethod(HttpProtocolConstants.HTTP_METHOD_GET);
                connection.setRequestProperty("WWW-Authenticate","OAuth realm=http://twitter.com/");
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    
                input = connection.openDataInputStream();
                int resp = connection.getResponseCode();
                if (resp == HttpConnection.HTTP_OK) {
                    StringBuffer buffer = new StringBuffer();
                    int ch;
                    while ( (ch = input.read()) != -1){
                        buffer.append( (char) ch);
                    }
                    String content = buffer.toString();
                    Const.token = content.substring(content.indexOf((Const.OAUTH_TOKEN+"="))+(Const.OAUTH_TOKEN+"=").length(), content.indexOf('&'));
                    Const.tokenSecret = content.substring(content.indexOf((Const.OAUTH_TOKEN_SECRET+"="))+(Const.OAUTH_TOKEN_SECRET+"=").length(), content.length());
    
                }else{
                      StringBuffer buffer = new StringBuffer();
                      int ch;
                      while ( (ch = input.read()) != -1){
                          buffer.append( (char) ch);
                      }
                      String content = buffer.toString();
                      System.out.println("request Error: " + content);
                }
                return Const.token;
                //return (getTwitterMessage(connection.getResponseCode()));
            } catch (IOException e) {
                return "IOexception";
            } catch (TransactionException nc) {
                return "noConnection";
            } catch (Exception e) {
                return "Exeption";
            } finally {
                try {
                    connection.close();
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
    public static ConnectionFactory getConfiguredConectionFactory(int timeout){
            int[] allow ={
                    TransportInfo.TRANSPORT_TCP_CELLULAR
            };
            int[] denny ={
                    TransportInfo.TRANSPORT_MDS,
                    TransportInfo.TRANSPORT_WAP,
                    TransportInfo.TRANSPORT_TCP_WIFI,
                    TransportInfo.TRANSPORT_WAP2,
                    TransportInfo.TRANSPORT_BIS_B
    
            };
            ConnectionFactory factory = new ConnectionFactory();
            factory.setEndToEndDesired(false);
            factory.setEndToEndRequired(false);
            factory.setPreferredTransportTypes( allow);
            factory.setDisallowedTransportTypes(denny);
            factory.setAttemptsLimit(3);
            factory.setConnectionMode(ConnectionFactory.ACCESS_READ_WRITE);
            factory.setTimeoutSupported(true);      
    
            factory.setTransportTypeOptions(TransportInfo.TRANSPORT_TCP_CELLULAR,telefonicaAPN );
            factory.setConnectionTimeout(timeout);
            factory.setTimeLimit(timeout);
                    return factory;
    }
    
    public static String oauth_header(String url, String method) {
            String nonce = nonce();
            long timestamp = timestamp();
            Hashtable pairs = new Hashtable();
    
            pairs.put(Const.OAUTH_CONSUMER_KEY, Const.consumerKey);
            pairs.put(Const.OAUTH_NONCE, nonce);
            pairs.put(Const.OAUTH_SIGNATURE_METHOD, Const.SIGNATURE_METHOD);
            pairs.put(Const.OAUTH_TIMESTAMP, Long.toString(timestamp));
            if(Const.token != null) {
                pairs.put(Const.OAUTH_TOKEN, Const.token);
                //pairs.put(OAUTH_VERIFIER, verifier);
            }
            pairs.put(Const.OAUTH_VERSION, "1.0");
            pairs.put(Const.OAUTH_CALLBACK, Const.CALLBACK_URL);
            String sig = signature(method, url, pairs);
            //pairs.put(Const.OAUTH_SIGNATURE, escape(sig));
    
            StringBuffer header_sb = new StringBuffer();
            if(method.equals("GET"))
            {
                String comma = ",";
                header_sb.append(Const.OAUTH_CONSUMER_KEY).append("=").append(URLUTF8Encoder.encode(Const.consumerKey)).append(comma);
                header_sb.append(Const.OAUTH_NONCE).append("=").append(nonce).append(comma);
                header_sb.append(Const.OAUTH_SIGNATURE).append("=").append(URLUTF8Encoder.encode(sig)).append(comma);
                header_sb.append(Const.OAUTH_SIGNATURE_METHOD).append("=").append(URLUTF8Encoder.encode(Const.SIGNATURE_METHOD)).append(comma);
                header_sb.append(Const.OAUTH_TIMESTAMP).append("=").append(Long.toString(timestamp)).append(comma);
                if(Const.token != null) {
                    header_sb.append(Const.OAUTH_TOKEN).append("=").append(URLUTF8Encoder.encode(Const.token)).append(comma);
                }
                header_sb.append(Const.OAUTH_VERSION).append("=").append("1.0").append(comma);;
                header_sb.append(Const.OAUTH_CALLBACK).append("=").append(URLUTF8Encoder.encode(Const.CALLBACK_URL));
            }
            else if(method.equals("POST"))
            {
                header_sb.append(Const.OAUTH_CONSUMER_KEY).append("=").append(URLUTF8Encoder.encode(Const.consumerKey)).append("&");
                header_sb.append(Const.OAUTH_NONCE).append("=").append(nonce).append("&");
                header_sb.append(Const.OAUTH_SIGNATURE).append("=").append(URLUTF8Encoder.encode(sig)).append("&");
                header_sb.append(Const.OAUTH_SIGNATURE_METHOD).append("=").append(URLUTF8Encoder.encode(Const.SIGNATURE_METHOD)).append("&");
                header_sb.append(Const.OAUTH_TIMESTAMP).append("=").append(Long.toString(timestamp)).append("&");
                if(Const.token != null) {
                    header_sb.append(Const.OAUTH_TOKEN).append("=").append(URLUTF8Encoder.encode(Const.token)).append("&");
                    //header_sb.append(OAUTH_VERIFIER).append("=").append(escape(verifier)).append("&");
                }
                header_sb.append(Const.OAUTH_VERSION).append("=").append("1.0").append("&");
                header_sb.append(Const.OAUTH_CALLBACK).append("=").append(Const.CALLBACK_URL);
            }
            return header_sb.toString();
        }
    

    Well I found the solution to al my headache, the phone are the incorrect time and that the reason for this same code fails in this terminal

  • Error trying to solve. + http + wifi

    Hi all

    up to now, am unable to establish a connection on the device. I have few things to understand before I go into details...

    (1) if the user has the APN settings, my application will connect to the Internet.

    (2) am using curve 8520 device, is not have APN settings, but it opens google and able to surf on the net. This means that the APN settings are only for applications to access the internet.

    (3) when I try to open my app Simulator, I got the exception "Error trying to resolve".

    the url is:

    "http://mypc5/BI/services/BIReport.asmx/GetChildReport?AccountId=12&Reportname=product_Report&Level=0&FLMasterDataId=0&SLMasterDataId=0&GroupItemId=0 &Rand=0;". = wifi interface.

    the exception is the following: I had the same exception.

    When I remove the suffix to the url, it is running in the Simulator. and in the device, I have exception "The Tunnel failed" .

    I used HttpConnection to establish the connection.

    Any help will be appreciated...

    A few quick tips:

    You asked

    "1) if the user is not APN settings, my application will connect to the Internet."

    A strand - review article and the vidoe and see how many ways there are for your application under connect to the internet

    You asked:

    "Am 2) using device curve 8520, is not have APN settings, but it opens google and able to surf on the net." This means APN settings are only for applications to access the internet. »

    A strand - review article and the vidoe and see how many ways there are for your application under connect to the internet

    You asked:

    "(3) when I try to open my app Simulator, I got the exception 'Error in trying to solve'. '.

    the url is:

    "http://mypc5/BI/services/BIReport.asmx/GetChildReport?AccountId=12&Reportname=product_Report&Level=0&FLMasterDataId=0&SLMasterDataId=0&GroupItemId=0 &Rand=0;". = wifi interface.

    the exception is the following: I had the same exception. »

    Hint - did you try cela in the Borwser, in fact any browser

    You asked:

    "When I remove the suffix to the url, it is running in the Simulator."and in the device, I have "Tunnel Failed" exception."

    A hint - see the section in the Thread that talks about what you can and can't do on the Simulator.  Also check the wire and the articles referenced to determine devices do when there is no suffix connection.

  • COD installed via CodeModuleManager has "error checking".

    I searched the forums for all the threads on CodeModuleManager and creation of modules by program. I managed to gather enough information to get the code below, but it still does not have 100%. For brevity, I've deleted the error handling code.

    I can run my code below and it creates modules. I'm not trying to install over a previous installation, it comes to intall the app for the first time. However, the application that installs it will not work when I click on the application of the new icon (the app is signed). When I click on the newly installed application icon, I get this error message on the home screen (the application never starts). The message reads the following:

    Error at startup MyApp: Module 'MyApp' has verification errors.

    But if I reboot the device or the Simulator and click the icon of newly installed, it works without problem. The newly installed application has another point of entry that runs at startup which is for a process in the background in the application.

    When I try this code with a different and much smaller application that is just a simple file of COD it works and I can run the newly installed application immediately after installation.

    But when there are several cod brothers I noticed a few interesting releases in the debugger console. In the loop where I call CodeModuleManager.saveNewModule, I see the following output from the debugger

    CMM: Add MyApp (3972)
    AC: new CRC = 557
    CMM: Add MyApp-1 (4010)
    AC: new CRC = 558
    From level 7
    From MyApp
    Research installed codfiles alias "MyApp-2".
    Research uninstalled codfiles alias "MyApp-2".
    Module "MyApp-2' not found." Error at startup MyApp: Module ' MyApp-2' not found. "
    MIDlet PushRegistry startup
    MIDlet startup PushRegistry finished
    From net_rim_process_launcher
    Net_rim_process_launcher (156) started
    CMM: Add MyApp-2 (4013)
    AC: new CRC = 559

    Note that after that MyApp-1 is added that you see level 7 starts and triggers another startup auto entry point. But now MyApp-2 is not yet added, and he complains about not finding the MyApp-2 module.

    This message on MyApp-2 is related to me being able to run the newly installed application until I reboot? If not, is there any ideas on why I can't launch the new application immediately?

    String[] codUrls = new String[] {    "http://www.example.com/MyApp.cod,    "http://www.example.com/MyApp-1.cod,    "http://www.example.com/MyApp-2.cod ");
    
    CodeModuleGroup codeModuleGroup = new CodeModuleGroup("MyApp");codeModuleGroup.setCopyright("2009 MyCompany");codeModuleGroup.setDescription("MyApp for BlackBerry");codeModuleGroup.setVendor("MyCompany");codeModuleGroup.setVersion("1.0.0");
    
    //limit first module to 60KB since it must be under 64KB as mentioned in docsint firstModuleMaxSize = 1024 * 60;
    
    HttpConnection httpConn = null;InputStream inputStream = null;
    
    int[] newModuleHandles = new int[codUrls.length];
    
    for (int i = 0 ; i < codUrls.length ; i++){    httpConn = (HttpConnection) Connector.open(codUrls[i], Connector.READ_WRITE, true);    httpConn.setRequestMethod(HttpConnection.GET);    int responseCode = httpConn.getResponseCode();    if (responseCode == HttpConnection.HTTP_OK)    {        int responseLength = (int) httpConn.getLength();        byte[] responseBytes = new byte[responseLength];        int bytesRead = inputStream.read(responseBytes); intputStream.close(); httpConn.close();        if (bytesRead > firstModuleMaxSize)        {            //write the first part            newModuleHandles[i] = CodeModuleManager.createNewModule(bytesRead, responseBytes, firstModuleMaxSize);            //write the rest            CodeModuleManager.writeNewModule(newModuleHandles[i], firstModuleMaxSize, responseBytes, firstModuleMaxSize, bytesRead - firstModuleMaxSize);        }        else        {     //less than 60KB so write it all in one module            newModuleHandles[i] = CodeModuleManager.createNewModule(bytesRead, responseBytes, bytesRead);        }    }}
    
    for (int i = 0 ; i < codUrls.length ; i++){    if (newModuleHandles[i] != 0)    {        CodeModuleManager.saveNewModule(newModuleHandles[i], true);    }}
    
    for (int i = 0 ; i < codUrls.length ; i++){    if (newModuleHandles[i] != 0)    {        String modName = CodeModuleManager.getModuleName(newModuleHandles[i]);        System.out.println("adding module " + modName);    codeModuleGroup.addModule(modName);    }}
    
    codeModuleGroup.store();
    

    It does not work because you are breaking modules in parties to the arbitrary limit (64 k) and then recording these pieces using the CodeModuleManager API as if they were modules.

    Things to keep in mind:

    * A COD file can contain one or more modules. If it contains several modules, then the COD file is just a ZIP file without compression and each module is a file entry in the ZIP file.

    * The CodeModuleManager API works on modules instead of COD files.

    Therefore, you need to need to get the COD modules or files and stream then one by one and without breaking any which module to pieces at CodeModuleManager. You could achieve this by ensuring that you download are simple-module-COD-files (e.g., unpack the composite cod on the web server), or you can download a COD file and then unzip it into modules on the device (uses more memory).

    PS You are unable to read the entry correctly HTTP: method (byte []) read from the input stream only is not guaranteed to read all the data that you have asked, so, on top of the arbitrary question above with modules into pieces, you couldn't even read the modules in its entirety. You will need to loop until you have read everything you wanted, or until the input stream is closed prematurely.

  • HttpConnection, OutputStream cannot process large files?

    I am trying to download images 2 MB + my flashlight (using the option of large default image of the device) to a server over WI-FI.  I use HttpConnection and OutputStream to write the data.

    It seems that the multipart http getting blurred with this large files.  When I change the settings of device in the Middle camera, everything works fine.

    No, my server isn't the problem.  I configured and tested, and it may take more than 5 MB files.

    I think that the problem is with HttpConnection/OutputStream.

    Here is the request of multiple parties for size MEDIUM (300-600 KB) images.   Note the JPEG image data after Content-Type.  Images of this size are downloaded.

    Looks like demand for LARGE images (camera > Options > Image size > Large) 1.9 to 2.5 MB in size.   Note the JPEG section disappeared after Content-Type.

    For files of this size, I get TCP Out-of-Order messages and my web server gives an error 400 (bad request.

    Relevant code:

           // write content        out = httpConn.openDataOutputStream();        out.write(getBoundaryMessage(fileKey, fileName, mimeType).getBytes());
    
            // file data        int size = 8196;        byte[] buffer = new byte[size];        int total = 0, count = 1;        in = fconn.openInputStream();        while (true)         {            int bytesRead = in.read(buffer, 0, size);            total += bytesRead;            if (total > 0 && bytesRead == -1)                 break;            out.write(buffer, 0, bytesRead);            result.setSent(total);        }
    
            // end boundary        out.write(getEndBoundary().getBytes());        out.flush();
    
            // send request and retrieve response        int rc = httpConn.getResponseCode();
    

    What is never tested anyone (from RIM) 2 + MB files in a single query of HttpConnection?  Someone else get it to work?

    what you set as ContentLength? Just the data image or dou also include you the size in bytes [] of your header and the walk around the pure image data?

  • Connection on error curve 9320 times

    Hello

    My smart phone BlackBerry curve 9320 got a vodaphone SIM, wifi is enabled. But when I try to establish an http connection, it is showing "connection timeout error. The connection works fine in the Simulator.

    s = Connector.open(reqStr+";deviceside=true;interface=wifi",Connector.READ_WRITE) (StreamConnection);
    httpConn s = (HttpConnection);

    If I do not add the parameter = wifi interface, then it displays "wifi not accessible to the general public".

    The browser of the unit works fine.

    Help, please.

    Before you start to look at this problem, I wonder if you are aware of all possibilities about the methods that applications can connect?  I recommend you to consider at least these two things:

    http://supportforums.BlackBerry.com/T5/Java-development/networking-transports-II/Ta-p/446742

    http://supportforums.BlackBerry.com/T5/Java-development/different-ways-to-make-an-HTTP-or-socket-con...

    If this is all familiar, then you have to determine what method you will use to connect.  Assuming you are trying to develop on OS 5.0 and above then you could use the ConnectionFactory or develop your own method to choose the connection.  Both work very well, but there are a number of Threads that talk about problems of connection with these.  I recommend you search around to find tips, you should find everything you need already in discussions in the forum.  .

  • HttpConnection MDS Service not available

    Hello

    Ive deployed an application to my Blackberry 9700.

    When I test the app I get an error ' MDS Service not available: u12f.

    I don't get this error when I use the Simulator.

    I use the following code.

    factory = DocumentBuilderFactory.newInstance();
    builder = factory.newDocumentBuilder();
    httpConnection = (HttpConnection) Connector.open(url+ ";ConnectionTimeout=9000");
    inputStream = httpConnection.openInputStream();
    document = builder.parse(inputStream);
    

    Strange thing is I have access to the internet and my phone is running through BES.

    What is a proxy thing? Y at - it code to determine that the device uses to access the internet?

    Please help me

    Thank you

    Ah ok, I realized that blackberry can connect to the internet in a number of ways, and the program should check for the latter.

    The answer of

    http://blog.accelgolf.com/2009/05/22/BlackBerry-cross-carrier-and-cross-network-HTTP-connection

    Thank you

Maybe you are looking for