Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Trusted Contributor
Davidf65
Posts: 151
Registered: ‎07-20-2010
My Device: Not Specified
Accepted Solution

Https post issue

hey guys I'm having trouble sending data to a backend server. I'm trying to send this data using the http post method. Now, the connection is working fine, its giving me a 200 OK response after which I try writing some data. But unfortunately the server doesnt get any data. My code is as follows:

 

String toSend = "Write this to the server";

byte[] postData = toSend.getBytes();

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

c.setRequestProperty("Content-Type","application/x-www-form-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.

 

Thanks

 

David

 

Developer
RexDoug
Posts: 4,764
Registered: ‎07-21-2008
My Device: Not Specified

Re: Https post issue

Get rid of the flush.

 

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

 

Like this:

 

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

// now you can close the stream

Developer
peter_strange
Posts: 19,609
Registered: ‎07-14-2008
My Device: Not Specified

Re: Https post issue

[ Edited ]

Agree with RexDoug, by getting the response code you are actually completing the connection - you need to write the posted data first.

 

Can I also suggest that you do not use DataOutputStream - just use the supplied OutputStream, then it won't try to do anything clever with the data. 

 

In code, here is what I would have:

 

c.setRequestMethod(HttpConnection.POST);

OutputStream os = c.openOutputStream();

os.write(postData);

os.flush();

os.close();

int responseCode = c.getResponseCode();

// You probably want to read some return data here before you close the connection. 

c.close();

Trusted Contributor
Davidf65
Posts: 151
Registered: ‎07-20-2010
My Device: Not Specified

Re: Https post issue

Thanks Peter and Rex its working now! much appreciated!