Simple HTTP (POST) connection

I have the code below, it connects to the correct php page, but the POST data is not getting through.

It's probably a syntax problem, but I can't get out.

If you need anything else to help study, just let me know.

Thank you

public void sendPostRequest() {
        HttpConnection hc = null;
        try {

            hc = (HttpConnection)Connector.open("http://www.example.com/index.php"+updateConnectionSuffix());
            URLEncodedPostData oPostData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
            oPostData.append("lat", "100");
            oPostData.append("long", "200");
            OutputStream strmOut = hc.openOutputStream();
            strmOut.write(oPostData.getBytes());
            strmOut.flush();
            strmOut.close();
            int blah = hc.getResponseCode();
            String returnMessage = hc.getResponseMessage();

        }

        catch (IOException ioe) {

        }
        finally {
            try {
                if (hc != null) hc.close();
            } catch (IOException ignored) {}
        }
}
private String updateConnectionSuffix(){
        String connSuffix = null;
        if (DeviceInfo.isSimulator()) {
            connSuffix = ";deviceside=true";
        } else {
            if ( (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) &&
                    RadioInfo.areWAFsSupported(RadioInfo.WAF_WLAN)) {
                connSuffix=";interface=wifi";
            } else {
                String uid = null;
                ServiceBook sb = ServiceBook.getSB();
                ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
                for (int i = 0; i < records.length; i++) {
                    if (records[i].isValid() && !records[i].isDisabled()) {
                        if (records[i].getUid() != null &&
                                records[i].getUid().length() != 0) {
                            if ((records[i].getCid().toLowerCase().indexOf("wptcp") != -1) &&
                                    (records[i].getUid().toLowerCase().indexOf("wifi") == -1) &&
                                    (records[i].getUid().toLowerCase().indexOf("mms") == -1) ) {
                                uid = records[i].getUid();
                                break;
                            }
                        }
                    }
                }
                if (uid != null) {
                    // WAP2 Connection
                    connSuffix = ";ConnectionUID="+uid;
                } else {
                    connSuffix = ";deviceside=true";
                }
            }
        }
        return connSuffix;
    }

}

Agree with RexDoug, and above all, you don't actually tell the http connection this is a POST.

You will find several examples of ribust code here:

http://supportforums.BlackBerry.com/T5/Java-development/sample-HTTP-connection-code-and-bis-B-access...

Here are a few additional lines, you will need;

hc.setRequestMethod (HttpConnection.POST);
hc.setRequestProperty (HttpProtocolConstants.HEADER_CONTENT_TYPE, oPostData.getContentType ());
postBytes Byte [] = oPostData.getBytes ();
hc.setRequestProperty (HttpProtocolConstants.HEADER_CONTENT_LENGTH, Integer.toString (postBytes.length));
OutputStream strmOut = hc.openOutputStream ();
strmOut.write (postBytes);
strmOut.flush ();
strmOut.close ();

Tags: BlackBerry Developers

Similar Questions

  • Simple HTTP post

    Does anyone know of a document/tutorial that shows you how to make a post of simple http form from a flex application?
    I guess it's possible to do a http post to a ColdFusion page that uses only the usual FORM variables to receive the data.

    After seeing this it would make life a lot easier to create "rich forms" in flex instead of DHTML, javascript & CSS.

    I see many examples of data by pulling in a flex front end, but not much focus on sending data.

    See you soon

    Simon

    I took this example and he wrote style CF.

    Works like a charm...

    See you soon...

  • Failure of HTTP post when connecting via SIP

    Hi all

    I'm doing HTTP post, but I get corrupted in the response data.

    This problem only occurs on the device (4.5) and only if you use the SIP configuration

    (the problem does not when you use a device via Wifi 4.6)

    Here is my code:

    HttpConnection connection = (HttpConnection)Connector.open(url + ";deviceside=false");connection.setRequestProperty("x-rim-transcode-content", "*/*");connection.setRequestMethod(HttpConnection.POST);connection.setRequestProperty("Content-Type","multipart/form-data; boundary=@---------------------------123");connection.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(data.length));      OutputStream os = connection.openOutputStream();os.write(data);
    
    if (connection.getResponseCode()==HttpConnection.HTTP_OK){   StringBuffer result = new StringBuffer();   byte[] buffer = new byte[2000];   int i = 0;         DataInputStream in = connection.openDataInputStream();
    
       while ((i = in.read(buffer)) != -1){      result.append(new String(buffer, 0, i,"ISO-8859-1"));   }}
    

    Does someone know what I'm doing wrong here?

    (BTW, the system cut the suffix HTTP "ConnectionType =" which should be equal to "mds" + "»' + 'public')

    I guess that your assumption that the "transcode-including" in the request header method caused the problem was correct.

    I changed the method request header, it shows the HttpConnection API:

    ...
    
    // Set the request method and headers
    c.setRequestMethod(HttpConnection.POST);
    c.setRequestProperty("If-Modified-Since","29 Oct 1999 19:43:31 GMT");
    c.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
    c.setRequestProperty("Content-Language", "en-US");
    
    ...
    

    and the problem has been corrected

  • Connect in HTTP-Post

    Hello

    am I right if I think that it is not possible to connect to rwservlet via http-post, only http-get.
    And that's the reason why I get REP-56048 when I try?

    Thank you.

    Concerning

    Chris

    Hi Chris,
    Take a look at the code in the following document can help.

    Reference
    REP-0788 warning message when the report with a form of parameter of the HTML form on the web (Doc ID 359819.1)

    Best regards, RZ

  • A form of Google with http POST VI

    Dear LabVIEW forum,

    I'm filling out a very simple form of Google consisting of 4 text fields named AI0 AI1, AI2 AI3.

    I use the http POST provided by LabVIEW VI:

    When I run this, a new row is added to the answer sheet, but values do not appear, with the exception of the timestamp.

    What I am doing wrong?

    Thank you!

    Hello

    I had a quick look at the form and text next to the entry boxes is AI0... but the names of the input text boxes aren't AI0 etc.. You may need to get the page first and then scan the page for the name of the entry.

    Mike

  • Sending parameter using the METHOD (HTTP POST = PROBLEM WEBSERVICE)

    Hello world

    I need help here

    I tried 1 week to the code to send the parameter but the error still result

    It sends no parameter at all the

    Heres my PPC

    ApplicationUI::ApplicationUI(bb::cascades::Application *app) :
            QObject(app)
    {
    
        m_pTranslator = new QTranslator(this);
        m_pLocaleHandler = new LocaleHandler(this);
    
        bool res = QObject::connect(m_pLocaleHandler, SIGNAL(systemLanguageChanged()), this, SLOT(onSystemLanguageChanged()));
        // This is only available in Debug builds
        Q_ASSERT(res);
        // Since the variable is not used in the app, this is added to avoid a
    
        Q_UNUSED(res);
    
        onSystemLanguageChanged();
    
        QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
    
        qml->setContextProperty("MyApp",this);
        // Create root object for the UI
        AbstractPane *root = qml->createRootObject();
    
        // Set created root object as the application scene
        app->setScene(root);
    }
    
    void ApplicationUI::post(const QString &fullName, const QString &email, const QString &password)
    {
        QNetworkAccessManager connection;
    
        QUrl url("http://www.rws.rajaspot.com/rs_usermanagementclient.php");
        QNetworkRequest req(url);
        //url.addQueryItem("parameter", "14");
    
        QByteArray postData;
    
        postData.append("method=rsnewuser&").append("fullName="+fullName).append("email="+email).append("password="+password);
    
        QNetworkReply* reply = connection.post(req, postData);
        bool ok = connect(reply, SIGNAL(finished()), this, SLOT(postFinished()));
        Q_ASSERT(ok);
        Q_UNUSED(ok);
    
    }
    
    /**
     * PostHttp::onGetReply()
     *
     * SLOT
     * Read and return the http response from our http post request
     */
    void ApplicationUI::postFinished()
    {
        QNetworkReply* reply = qobject_cast(sender());
    
        /* QString response;
        if (reply) {*/
            if (reply->error() == QNetworkReply::NoError) {
                QString result = reply->readAll();
    
                /*const int available = reply->bytesAvailable();
                if (available > 0) {
                    const QByteArray buffer(reply->readAll());
                    response = QString::fromUtf8(buffer);
                }*/
            } else {
                int errorCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
                qDebug() << errorCode << endl << reply ->errorString();
            }
    
            reply->deleteLater();
        }
    
    void ApplicationUI::onSystemLanguageChanged()
    {
        QCoreApplication::instance()->removeTranslator(m_pTranslator);
        // Initiate, load and install the application translation files.
        QString locale_string = QLocale().name();
        QString file_name = QString("UsernamePHP_%1").arg(locale_string);
        if (m_pTranslator->load(file_name, "app/native/qm")) {
            QCoreApplication::instance()->installTranslator(m_pTranslator);
        }
    }
    

    Heres my hpp

    #ifndef ApplicationUI_HPP_
    #define ApplicationUI_HPP_
    
    #include 
    
    namespace bb
    {
        namespace cascades
        {
            class Application;
            class LocaleHandler;
        }
    }
    
    class QTranslator;
    
    /*!
     * @brief Application object
     *
     *
     */
    
    class ApplicationUI : public QObject
    {
        Q_OBJECT
    public:
        ApplicationUI(bb::cascades::Application *app);
        virtual ~ApplicationUI() { }
    public:
        Q_INVOKABLE void post(const QString &fullName, const QString &email, const QString &password);
    
      Q_SIGNALS:
                void complete(const QString &info);
      private Q_SLOTS:
                void postFinished();
    
    private slots:
           void onSystemLanguageChanged();
    
    private:
        QTranslator* m_pTranslator;
        bb::cascades::LocaleHandler* m_pLocaleHandler;
    };
    
    #endif /* ApplicationUI_HPP_ */
    

    and this is my my main.qml

    Button{
                id : button
                text : "Register"
                onClicked: {
                   MyApp.post(tf1.text,tf2.text,tfpass.text)
    
                }
                horizontalAlignment: HorizontalAlignment.Center
            }
    

    I need to send the parameter to http://www.rws.rajaspot.com/rs_usermanagementclient.php

    but its like divider by 2, the parameter 'method = rsnewuser' and the content is fullName, email, and password

    What a success, it will show on http://www.rws.rajaspot.com/rs_userclient.php but I try this error code again

    any ideas what should I do?

    Thank you

    I mean not to define QNetworkAccessManager inside the function.

    For example:

    Declare the pointer to QNetworkAccessManager in your header file (all)

    QNetworkAccessManager *connection;
    

    and then set it in the constructor of the app inside the function you or you. In the second case, you must remove QNetworkAccessManager pointer after postFinished. (connection-> deleteLater())

    connection = new QNetworkAccessManager(this);
    

    and the full code of the POST function

    ...post(const QString &fullName, const QString &email, const QString &password)
    {
        QUrl url("http://www.rws.rajaspot.com/rs_usermanagementclient.php");
    
        QUrl postParams;
        postParams.addQueryItem("method", "rsnewuser");
        postParams.addQueryItem("fullName", fullName);
        postParams.addQueryItem("email", email);
        postParams.addQueryItem("password", password);
    
        QNetworkRequest req(url);
        req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    
        QNetworkReply* reply = connection->post(req, postParams.encodedQuery());
        bool ok = connect(reply, SIGNAL(finished()), this, SLOT(postFinished()));
        Q_ASSERT(ok);
        Q_UNUSED(ok);
    }
    

    It may be useful

     

  • HTTPS post problem

    Hey guys I have problems to send data to a back-end server. I am trying to send the data using the http post method. Now, the connection works fine, her gives me a 200 OK response, after which I try to write data. But unfortunately the server receives all the data. My code is as follows:

    String toSend = "write it to the server";

    Byte [] postData = toSend.getBytes ();

    c = (HttpsConnection) Connector.open ("https://myurl;deviceside=true");

    c.setRequestProperty ("Content-Type", "application/x-www-formulaires-urlencoded");
    c.setRequestProperty ("Content-Language", "en-US");
    c.setRequestProperty ("Content-Length", String.valueOf (postData.length));
    c.setRequestMethod (HttpConnection.POST);
    int responseCode = c.getResponseCode ();

    dStr = new DataOutputStream (c.openOutputStream ());
    dStr.write (postData);

    dStr.flush ();
    dStr.close ();

    c.Close ();

    Am I missing something here? Help would be greatly appreciated.

    Thank you

    David

    Get rid of the flush.

    do the "getResponse" before closing the stream. This void anyway.

    Like this:

    Set the properties of the application
    setRequestProperties (m_httpConnection);
                           
    dataOutputStream = m_httpConnection.openDataOutputStream ();
    writeRequestPayload (dataOutputStream);
       
    get and store the response for this request code
    m_responseCode = m_httpConnection.getResponseCode ();

    Now you can close the stream

  • HTTPS post doesn't work on device but in the Simulator

    You are looking for suggestions on why a https post works all the time on a simulator, but what installation on the device and test it works the first time but the time the rest of the time after that.

    Here is most of the code, this came from another sample written and posted on BB forums.

    I tried with the removed ConnectionTimeout, and with it the value of different values.

    As mentioned it works the first two times, maybe even just the first time and not after once using the real device.

    Any thoughts would be greatly appreciated.

    private String of doTransaction (postString String)]
    {
    String [] ccResponse;
    HttpsConnection SC;
    OutputStream outStream = null;
    String url = "https://url/; ConnectionTimeout = 60000 "; just removed the url to view the code

    Try
    {
    HC = (HttpsConnection)
    Connector.Open (url, Connector.READ_WRITE); Set the POST request method
    hc.setRequestMethod (HttpsConnection.POST);
    hc.setRequestProperty ("Content-Type", "application/x-www-formulaires-urlencoded");
    hc.setRequestProperty ("Content-Length", Integer.toString (postString.length ()));

    outStream = hc.openDataOutputStream ();
    outStream.write (postString.getBytes ());
    outStream.flush ();
    outStream.close ();
    Get the answer back to the servlet
                
    hc.getResponseCode ();
                
                
    InputStream is = hc.openDataInputStream ();
    LineReader lr = new LineReader (is);

    While (true)

    {
    Try
    {
    Byte [] arr = lr.readLine ();
    String $thisline = new String (arr);
    Dialog.Inform ($thisline);
    If (! thisLine.endsWith ("="))
    {
    Dialog.Inform ("splitting");
    If ends with =, not split
    String [] splitLineResponse;
    String separator = '=';
    splitLineResponse = split (new String (arr), separator);

    String responseItem = splitLineResponse [0];
    String responseValue = splitLineResponse [1];

    There are a lot of topics split here.

    }
                        
                            
    }
    catch (e EOFException)
    {
    Reached end of file
    Dialog.Inform ("expressions of folklore Exception" + e.getMessage ());
    break;
    }
    }
    HC. Close();
                
    }
    catch (Exception ex)
    {
    Transaction time-out
    Dialog.Alert ("TransException" + ex.getMessage ());

    }
    postData = null;
    Return ccResponse;
            
    }

    How is it a failure?

    My guess is that the problem is that the unit does not have a connection. Without any connection parameter, it will connect via MDS if the device is a network of MDS; If not, he'll probably try direct TCP. In the latter case, it will fail unless the APN settings are set correctly. The carrier may also have something to say about it.

    I suggest you read the post-it by Peter Strange and also check out the videos of transport network that RIM posted. They provide a lot of information on how to establish connections.

  • HTTPS Post does not work in the OFA Page

    Hi all

    I created a Page of the OFA, by clicking on button I do next.

    //--------------------------------------------------------
    private static String contactService(String xmlInputString) throws Exception {}
    String outputStr = null;
    OutputStream outputStream = null;
    try {}

    URL url = new URL ("https://wwwcie.ups.com/ups.app/xml/ShipConfirm");

    HttpURLConnection connection = () (HttpURLConnection) url.openConnection;
    System.out.println ("Customer connection established with" + url.toString ());
    Configure the HTTP POST parameters
    connection.setDoOutput (true);
    connection.setDoInput (true);
    connection.setUseCaches (false);

    outputStream = connection.getOutputStream ();
    outputStream.write (xmlInputString.getBytes ());
    outputStream.flush ();
    outputStream.close ();
    System.out.println ("Http status =" + connection.getResponseCode () + "" + connection.getResponseMessage ());

    outputStr = readURLConnection (connection);
    System.out.println ("Response..." + outputStr);
    } catch (Exception e) {}
    System.out.println ("error sending data to the server..." + e.getMessage ());
    throw e;
    } {Finally
    If (outputStream! = null) {}
    outputStream.close ();
    outputStream = null;
    }
    }
    Return outputStr;
    }

    //----------------------------------------------------
    public static String readURLConnection (URLConnection uc) throws Exception {}
    StringBuffer buffer = new StringBuffer();
    BufferedReader reader = null;
    try {}
    reader = new BufferedReader (new InputStreamReader (uc.getInputStream ()));
    Letter int = 0;
    reader.readLine ();
    While ((letter = reader.read ())! = - 1) {}
    Letter from buffer. Append ((Char));
    }
    Reader.Close ();
    } catch (Exception e) {}
    System.out.println ("could not read from URL:" + try ());
    throw e;
    } {Finally
    If (reader! = null) {}
    Reader.Close ();
    Reader = null;
    }
    }
    Return buffer.toString ();
    }

    Now, when I run this JDEVELOPER local it works fine, but when when depolyed on the server, then when I click the button then page gets hanged and it does nothing.
    Is there any setting I should do in APPS environment. or anyone had done the same. any help will be appreciated.

    Thank you
    Vijay chraibi

    Hello

    If your code works fine in JDev and it does not work on the instance, then you can trigger SR with Oracle for Ptoduct JDeveloper.

    Kind regards
    Out Sharma

  • Network.http.Max - connections by-server not found in 27 FF

    Tried searching Network.http.Max - connections-per-server in the subject: config. This has been deleted?

    See:

  • necessary to enhance Network.http.Max - connections-per-server to javascript

    I have an AJAX web application which is very sensitive the number of connections allowed by the browser. Bad things happen when the limit is set at the bottom: frozen screens, the uncommitted transactions, deadlocks, etc..

    To avoid this, I need to check the current value of the configuration parameter "Network.http.Max - connections-per-server" program (i.e. javascript code) and to reject a request if the limit is too low with the instructions appropriate for the user.

    I guess that's possible because "subject: config" restores all values of settings and even allows for user to change. However, the code-behind for the page is very complicated, so I can not understand how to accomplish my task. All I need is a function or a method returns the current value of a given configuration parameter.

    Any help will be greatly appreciated.

    Anatoly

    You do not have access to the pref the subject: config page via a Web site.

    In theory it is possible, but the user get a pop-up and must confirm each time.

    See also http://www.mozilla.org/projects/security/components/signed-scripts.html

  • Authentication http post VI errors

    I am trying to query a web service to third parties non-LabVIEW LabVIEW 2014, using HTTP POST. Using another utility (restclient-ui-3.5-jar-with-dependencies.jar), I checked that URL, user name, password, and query syntax are accurate and are running on the same computer where my VI fails. I must be missing something when translating that to LV, because I get the error 401 (full authentication is required) and also 415 (unsupported media type).

    I have attached the configuration file used for the other utility, my VI and an overview of the response from the Web service for the post of the VI.  I had to make all anonymous, hide url, user, etc., so it can not really be tested as it is, unfortunately. I tried with & without additional authentication header, with & without Config SSL, etc. You can see the different options on the VI.

    Any suggestions?

    Thank you very much.

    Solved my problem with a combination of different required headers and syntax fixes.

  • Getting 7 error with the HTTP POST vi method when deplyed ISO crio as executable... urgent!

    Hi all

    I have an application where I can access the net server point of LabVIEW via the HTTP protocol to send the data. My application works fine when I run it on XP, and also sometimes on cRIO. I'm writing and reading files to store and read data from the server.

    When I do my application executable and deployed on cRIO I am constantly 7 error that says "Error in the node library function to call at the POST vi LabVIEWHTTPCLIENT".

    After getting this error if I try to run the my new project the crio (not through exe) I keep getting the same error. This means once the executable file is deployed on the crio, I get the error in my project application which was working fine before you deploy the executable file.

    7 occurs very frequently. and I am unable to find the reason. I gave all the paths in the constant form located on crio and files accessible also when the application is run.

    Is someone can you please help me what this error 7?

    as a result, that it is bound to the HTTP POST vi method...

    How can it be fix?

    Its quite urgent...

    Thanks in advance.

    Solution is provided by the NOR... Vi POST method missing two files that need to be there in the startup of the CRIO.insted folder there is in the system folder. That's why when running the exe that the startup on crio application it gives error as the files are not there. The fix for this HTTP POST vi update isn't out yet EITHER.

  • HTTP Post documentation does not mention the forums (BUG)

    Documents of the VI of HTTP post (see here) do not mention that there are 2 instances of this VI. It contains only the help on the string instance.

    Right-click on the VI shows that it is a polymorphic VI, with a buffer (string) and the instance of the file (paths).

    Aid for these screws would normally have a ring "Instance" where you could see that there are other forums. (example)

    This absence made me several hours of debugging, because the buffer method stops playback of the chain after finding a NULL byte. (this could be a separate bug).

    In my opinion all polymorphic screws should show their terminal selector.

    Tone

    Your dear,

    I reported the problem of documentation in corrective action request # 244384. I'll have another look in the question on the search for the null byte. Thank you for bringing this place.

    Best regards

  • Problem when using SOAP requests with HTTP POST function

    Hello!

    Using the vi of HTTP POST to send SOAP requests to a device, I encountered a problem.

    Take care of the HTTP header for you HTTP POST vi and defines the type of 'content' as "Content-Type: application/x-www-formulaires-urlencoded. Who is considered to be 'non-soap' requests by some Web servers.

    Standards W3C says in this case, you should be content-type: "application/soap + xml".

    Link to the page to W3C standard: http://www.w3.org/TR/soap12-part0/#L26866

    That is possible to update this feature in a future release so that programmers can choose (or type) the necessary content type?

    Have you tried "Add header" to change?

    http://zone.NI.com/reference/en-XX/help/371361L-01/lvcomm/http_client_addheader/

Maybe you are looking for

  • Qosmio G40-108 does not start

    Hi Gang I hope that there is some good buddies out there that can save a window double glazing to be mullared by that lappy.I had (Qosmio G40-108 with 4 GB of RAM) since August 2007. Everything was fine until two weeks about where it kept crashing du

  • dc5800 sff: bios dc5800

    I'll try to find an update of the bios for my dc5800 refurb, I now have 1.4 and have seen mention of a 1.59, but he can't find anywhere. I am a network technician, it's kinda an odd stub. Thank you!

  • Accidental deletion of files

    Hi people, I accidentally deleted some files in EZmedia NAS. Trash? Any application? Nothing to do? Thank you!

  • problems printing to the shared printer Hello on el capitan

    Since the upgrade to El Capitan, I can't use the printer shared via Hello.  The printer works from the computer it is attached to via the usb port.I can see and choose the printer from the other computer, but when the file gets to the proxy of the pr

  • To access the files on Western Digital MYBOOK 500 GB external drive

    I'm on a PC running Svc Pack 3 Windows XP and had a Western Digital MYBOOK 500 GB external drive connected works very well andthen I moved my PC set-up to another room and my problem began. When I turn on the system detects now the MYBOOK so I sent a