BlackBerry consume wcf - blackberry

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.

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

None of code can establish http connection over BIS

I am new in developing Blackberry Application.
In these three days, I already searched and learned in both forum and tutorial from the RIM itself. But none of them can solve my problem. >.<
So. I already tried some different methods to establish http connection over BIS in 4.6.
These are the following codes:
1.
HttpConnection httpConnection;
String url = "myURL;deviceside=true";
try{
httpConnection = (HttpConnection) Connector.open(url);
Dialog.inform(">.<");
}
catch(Exception e)
{
Dialog.inform(e.getMessage());
}
From the code #1 above, none of the dialogs are displayed.
String url = "myURL";
try {
StreamConnection s = (StreamConnection)Connector.open(url);
InputStream input = s.openInputStream();
Dialog.inform("sblm byte");
byte[] data = new byte[256];
int len = 0;
StringBuffer raw = new StringBuffer();
Dialog.inform("stlh buat byte");
while( -1 != (len = input.read(data))) {
raw.append(new String(data, 0, len));
}
Dialog.inform("stlh while");
response = raw.toString();
Dialog.inform(response);
input.close();
s.close();
}
catch(Exception e) { }
As well as code #1, this code above also doesnt pop up any dialog.
I am desperately need the right guide for establishing simple http connection. Is there any technique that I missed? Do I need any signature for this? Do I need extra setting in both my Blackberry device (BB 8900 with OS 5.00) or in my compiler, Eclipse?
Thank you.
Try this code.
try {
HttpConnection httpConnection=(HttpConnection)Connector.open(url);
httpConnection.setRequestMethod(HttpConnection.GET);
if(httpConnection.getResponseCode()==HttpConnection.HTTP_OK)
{
InputStream is=httpConnection.openInputStream();
int ch;
StringBuffer buffer=new StringBuffer();
while((ch=is.read())!=-1)
{
buffer.append((char)ch);
}
}
} catch (IOException e) {
System.out.println("Exception From Thread"+e);
e.printStackTrace();
}
}

wifi doesn't work in own apps, but works in blackberry's browser

we have just started to write Blackberry apps and got strange situation. Our apps work with mobile internet (GPRS, 3G, EDGE) but are not working using wifi connection.
I have tried to change all the settings. But still usually it is just "Tunnel failure" or "connection timed out" errors. The same is with HTTPDemo example.
Could someone help and explain what it is with Blackberry and WiFi?
StreamConnection s = null;
s = (StreamConnection)Connector.open(getUrl() +";interface=wifi");
HttpConnection httpConn = (HttpConnection)s;
int status = httpConn.getResponseCode();
if (status == HttpConnection.HTTP_OK)
{
// Is this html?
String contentType = httpConn.getHeaderField(HEADER_CONTENTTYPE);
boolean htmlContent = (contentType != null && contentType.startsWith(CONTENTTYPE_TEXTHTML));
InputStream input = s.openInputStream();
byte[] data = new byte[256];
int len = 0;
int size = 0;
StringBuffer raw = new StringBuffer();
while ( -1 != (len = input.read(data)) )
{
// Exit condition for the thread. An IOException is
// thrown because of the call to httpConn.close(),
// causing the thread to terminate.
if ( _stop )
{
httpConn.close();
s.close();
input.close();
}
raw.append(new String(data, 0, len));
size += len;
}
raw.insert(0, "bytes received]\n");
raw.insert(0, size);
raw.insert(0, '[');
content = raw.toString();
if ( htmlContent )
{
content = prepareData(raw.toString());
}
input.close();
}
else
{
content = "response code = " + status;
}
s.close();
}
catch (IOCancelledException e)
{
System.out.println(e.toString());
return;
}
catch (IOException e)
{
errorDialog(e.toString());
return;
}
Connecting the following way works for me
HttpConnection connection = null;
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connection = (HttpConnection) Connector.open(url+ ";interface=wifi",
Connector.READ_WRITE,true);
} else {
connection = (HttpConnection) Connector.open(url+";deviceside=true", Connector.READ_WRITE,true);
}
Please refer the following resource for in-depth understanding and various methods.
Sample HTTP Connection code and BIS-B Access By peter_strange

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

Blackberry send a HTTPPost request

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

Resources