Blackberry send a HTTPPost request - blackberry

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

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.

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;
}

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());
}
}

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.

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();

Related

local connection timed out after 120000 while reading the the image from the remote server

I am developing an application in BlackBerry 5.0 and want to display an image from a url. While reading the image from the url using the httpconnection I get the exception "local connection timed out after 120000 "
The exception occurs on the line "httpConnection.getResponseCode()".
My code is as follows :
private byte[] getimagefromurl(String PhotoUrl)
{
String url = "http://www.mywebsite.com/images/Folder/xyz.jpg";
try
{
httpConnection = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
System.out.println("url>>>>>>>> "+url);
httpConnection.setRequestMethod(HttpConnection.GET);
System.out.println("Response>>>>>>>> "+String.valueOf(httpConnection.getResponseCode()));
if(httpConnection.getResponseCode() == HttpConnection.HTTP_OK)
{
InputStream input = httpConnection.openInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int j = 0;
while((j=input.read()) != -1)
{
baos.write(j);
}
byteArray = baos.toByteArray();
baos.close();
}
}
catch(Exception e)
{
System.out.println("in catch>>>>"+e.toString());
}
return byteArray;
}
append url extension like following example is work when you r working with WIFI
httpConnection = (HttpConnection) Connector.open(url+";interface=wifi", Connector.READ_WRITE);
extensions just check this url
connection extensions
Yes the answer is exactly that. The connection timed out. check that your webservice works. if you are testing from device or emulator ,make sure you can hit the URL from the default blackberry browser.
If you are testing in the emulator, make sure you have MDS-CS simulator started.
have a look at this bit of code which works
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
public class HTTPClient {
public static String getPage(String url) {
String response = "";
try {
StreamConnection s = (StreamConnection)Connector.open(url);
InputStream input = s.openInputStream();
byte[] data = new byte[256];
int len = 0;
StringBuffer raw = new StringBuffer();
while( -1 != (len = input.read(data))) {
raw.append(new String(data, 0, len));
}
response = raw.toString();
input.close();
s.close();
} catch(Exception e) { }
return response;
}
}

BlackBerry consume wcf

I am working with OS 5.0 and I am trying to get some info from a wcf.
On the emulator it works like a champ, but on a device, with wifi connected, I get the error:
APN is not specified
my code:
HttpConnection con = null;
InputStream is = null;
try {
con = (HttpConnection) Connector.open(url);
final int responseCode = con.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK) {
System.out.println(responseCode);
}
is = con.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = is.read(responseData))) {
rawResponse.append(new String(responseData, 0, length));
}
final String result = rawResponse.toString();
_labelField.setText(result);
} catch (final Exception ex) {
System.out.println(ex.getMessage());
_labelField.setText(ex.getMessage());
} finally {
try {
is.close();
is = null;
con.close();
con = null;
} catch (Exception e) {
}
}
Check this article "Different ways to make HTTP Socket Connection". This article would help you understand how to make network connections if you are on BES network or BIS or WiFi or 3G network etc.
Getting back to your problem, if you want to connect through Wi-Fi, you will need to modify your connection url. Replace the following:
con = (HttpConnection) Connector.open(url);
With this:
con = (HttpConnection) Connector.open(url+";interface=wifi");
Now it would work on device with Wi-Fi connectivity.

An error in Blackberry during HttpConnection message contains Datagram(ConnectionBase).receive (Datagram) line 538

This is my code where the connection problem occuring.
HttpConnection is not getting a response from an connection obj in a input stream. The occuring error is:
Datagram(ConnectionBase).receive (Datagram) line 538
HttpConnection httpCon = null;
InputStream iStream = null;
String url = null;
String result = "";
public GetXmlHttp(String str)
{
url=str;
}
public String RESULT()
{
try
{
httpCon = (HttpConnection)Connector.open(url);
httpCon.setRequestMethod(HttpConnection.GET);
iStream = httpCon.openInputStream();//error is here
int httpResponse = httpCon.getResponseCode();
System.out.println("httpResponse code"+httpResponse);
System.out.println(httpResponse);
if(httpResponse != 200)
return null;
InputStreamReader in = new InputStreamReader(iStream);
StringBuffer sb=new StringBuffer();
char[] ch=new char[1020];
while(in.read(ch)!=-1)
{
sb.append(ch);
}
}
}
Posting the exception would help, but allso have a look at the API documentation for HttpConnection. There is sample code posted there for getting via an HttpConnection which has at least one significant difference from yours. getResponseCode is called before openInputStream:
void getViaHttpConnection(String url) throws IOException {
HttpConnection c = null;
InputStream is = null;
int rc;
try {
c = (HttpConnection)Connector.open(url);
// Getting the response code will open the connection,
// send the request, and read the HTTP response headers.
// The headers are stored until requested.
rc = c.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
is = c.openInputStream();

Retrieve GPS Location and send it to Web Server [duplicate]

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
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.
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;
}
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());
}
}
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.
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();

Retriving url from webservice and how to connect to that url

i am new to black berry.i am doing one task,i have one webservice to show some url.i need to retrive it and connect to that url.i tried with two threads one is to retrive url and other is to connect to url which is in webservice but it shows nullpointer exception.please help me.
Thank You.
since you have not posted any code, it's very difficult to diagnose the problem. But look at the following code which tries to open an absolute url. This can be helpful.
Use this method for both of your connection (Web Service and URL returned from Web Service). Be sure to call this method in a separate thread otherwise it will freeze the UI.
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 simulator is running
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;
}

Resources