Blackberry send a HTTPPost request
Asked Answered
C

5

3

i am developing and app for blackberry and i need to send a Http Post Request to my server. I'm using the simulator in order to test my app and i found this code in order to send request:

http://vasudevkamath.techfiz.com/general/posting-data-via-http-from-blackberry/

But i can't get it work, because it fails in this line:

int rc = _httpConnection.getResponseCode();

Any idea?

thanks

Christlike answered 15/2, 2011 at 15:30 Comment(3)
What is the error you are getting? What happens at this line?Lampley
Yes, what is happening? Also, are you invoking the method postData() on the event thread, or do you start up a separate thread? HTTP access on the event thread will cause problems.Abyss
Also getting this problem. Thread (not UI) waits at httpConn.getResponseCode(); for awhile then exits with Exception: java.io.InterruptedIOException: Local connection timed out after ~ 120000. Server is accessible from the browser on the simulator. I'm using code similar to the answers below. @xger86x did you figure this one out?Successive
F
2

Here is a sample code on how to send a POST request:

HttpConnection c = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
c.setRequestMethod(HttpConnection.POST);
OutputStream os = c.openOutputStream();
os.write(request.getBytes("UTF-8"));
os.flush();
os.close();
InputStream is = c.openInputStream();

Just make sure you use this code in a separate thread.

Fireeater answered 23/2, 2011 at 0:45 Comment(1)
How do you set POST parameters?Madoc
P
2
public static ResponseBean sendRequestAndReceiveResponse(String method, String absoluteURL, String bodyData, boolean readResponseBody) 
throws IOException
{
    ResponseBean responseBean = new ResponseBean();
    HttpConnection httpConnection = null;

    try
    {

        String formattedURL = absoluteURL + "deviceside=true;interface=wifi"; // If you are using WiFi
        //String formattedURL = absoluteURL + "deviceside=false"; // If you are using BES
        //String formattedURL = absoluteURL + "deviceside=true"; // If you are using TCP

        if(DeviceInfo.isSimulator()) // if you are using simulator
            formattedURL = absoluteURL;

        httpConnection = (HttpConnection) Connector.open(formattedURL);

        httpConnection.setRequestMethod(method);

        if (bodyData != null && bodyData.length() > 0)
        {                               
            OutputStream os = httpConnection.openOutputStream();
            os.write(bodyData.getBytes("UTF-8"));
        }           

        int responseCode = httpConnection.getResponseCode();
        responseBean.setResponseCode(responseCode);

        if (readResponseBody)
        {
            responseBean.setBodyData(readBodyData(httpConnection));
        }
    }
    catch (IOException ex)
    {                       
        System.out.println("!!!!!!!!!!!!!!! IOException in NetworkUtil::sendRequestAndReceiveResponse(): " + ex);
        throw ex;
    }
    catch(Exception ex)
    {                       
        System.out.println("!!!!!!!!!!!!!!! Exception in NetworkUtil::sendRequestAndReceiveResponse(): " + ex);
        throw new IOException(ex.toString());
    }
    finally
    {
        if (httpConnection != null)
            httpConnection.close();
    }

    return responseBean;
}

public static StringBuffer readBodyData(HttpConnection httpConnection) throws UnsupportedEncodingException, IOException
{   
    if(httpConnection == null)
        return null;

    StringBuffer bodyData = new StringBuffer(256);                          
    InputStream inputStream = httpConnection.openDataInputStream();

    byte[] data = new byte[256];
    int len = 0;
    int size = 0;

    while ( -1 != (len = inputStream.read(data)) )
    {
        bodyData.append(new String(data, 0, len,"UTF-8"));
        size += len;
    }

    if (inputStream != null)
    {
        inputStream.close();            
    }

    return bodyData;
}
Pegram answered 24/2, 2011 at 9:32 Comment(1)
Be sure to invoke this method in a separate thread and before updating UI you must get eventLock using Application.getUiApplication.getEventLock();Pegram
S
1

I know this question is pretty old and OP probably solved it by now, but I've just run into the same problem and managed to fix it!

You need to append ;deviceside=true to your URL.

So for example, your URL will change from "http://example.com/directory/submitpost.php" to "http://example.com/directory/submitpost.php;deviceside=true".

I found this here: http://supportforums.blackberry.com/t5/Java-Development/Different-ways-to-make-an-HTTP-or-socket-connection/ta-p/445879

My POST request was timing out after 3 minutes when I did not have this (See My Comment), but it works fine with this appended to the url.

I would also recommend using ConnectionFactory. Here's some of my code:

Network.httpPost("http://example.com/directory/submitpost.php;deviceside=true", paramNamesArray, paramValsArray)
public static void httpPost(String urlStr, String[] paramName, String[] paramVal) throws Exception {
        ConnectionFactory conFactory = new ConnectionFactory();
        conFactory.setTimeLimit(1000);
        HttpConnection conn = (HttpConnection) conFactory.getConnection(urlStr).getConnection();
        conn.setRequestMethod(HttpConnection.POST);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < paramName.length; i++) {
            sb.append(paramName[i]);
            sb.append("=");
            sb.append(paramVal[i]);
            sb.append("&");
        }
        byte[] postData = sb.toString().getBytes("UTF-8");
        conn.setRequestProperty("Content-Length",new Integer(postData.length).toString());

        OutputStream out = conn.openOutputStream();
        out.write(postData);
        //out.flush();      //Throws an Exception for some reason/Doesn't do anything anyways
        out.close();

        //This writes to our connection and waits for a response 
        if (conn.getResponseCode() != 200) {
            throw new Exception(conn.getResponseMessage());
        }
}
Successive answered 9/8, 2012 at 19:41 Comment(0)
S
0

Not sure about the site you posted, but I've successfully used the sample ConnectionFactory code provided on the blackberry site.

http://supportforums.blackberry.com/t5/Java-Development/Sample-Code-Using-the-ConnectionFactory-class-in-a-BrowserField/ta-p/532860

Just make sure not to invoke the connection on the EventThread.

Selfappointed answered 16/2, 2011 at 23:47 Comment(0)
F
0

That's how you add parameters, Full answer is here:

StringBuffer postData = new StringBuffer();

                    httpConn = (HttpConnection) Connector.open("https://surveys2.kenexa.com/feedbacksurveyapi/login?");
                    httpConn.setRequestMethod(HttpConnection.POST);

                    postData.append("username="+username);
                    postData.append("&password="+pass);
                    postData.append("&projectcode="+projectid);
                    String encodedData = postData.toString();

                    httpConn.setRequestProperty("Content-Language", "en-US");
                    httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                    httpConn.setRequestProperty("Content-Length",(new Integer(encodedData.length())).toString());
                    byte[] postDataByte = postData.toString().getBytes("UTF-8");

                    OutputStream out = httpConn.openOutputStream(); 
                    out.write(postDataByte);
                    out.close();

                    httpConn.getResponseCode();
Foodstuff answered 14/12, 2012 at 7:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.