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

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

Related

convert the bytes in to readable string format in blackberry?

I am working on an BB app in which I need to maintain a HTTP connection and with a name of image which is stored on server to get the text written in that image document.
I am getting the response in RTF format.
When I directly hit the server on open browser Chrome, I RTF file get downloaded.
Now I needs to perform that programetically,
1) Either convert the bytes which are coming in response in a simple string format so that I can read that.
or
2) Download the file as its happening on the browser manually so that by reading that file I read the information written in the document.
please suggest me how can I read the data from server by hitting any URL?
Currently I am working with this code:
try {
byte []b = send("new_image.JPG");
String s = new String(b, "UTF-8");
System.out.println(s);
} catch (Exception e) {
e.printStackTrace();
}
public byte[] send(String Imagename) throws Exception
{
HttpConnection hc = null;
String imageName = "BasicExp_1345619462234.jpg";
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] res = null;
try
{
hc = (HttpConnection) Connector.open("http://webservice.tvdevphp.com/basisexpdemo/webservices/ocr.php?imgname="+imageName);
hc.setRequestProperty("Content-Type", "multipart/form-data;");
hc.setRequestMethod(HttpConnection.GET);
int ch;
StringBuffer sb= new StringBuffer();
is = hc.openInputStream();
while ((ch = is.read()) != -1)
{
bos.write(ch);
sb.append(ch);
}
System.out.println(sb.toString());
res = bos.toByteArray();
}
catch(Exception e){
e.printStackTrace();
}
finally
{
try
{
if(bos != null)
bos.close();
if(is != null)
is.close();
if(hc != null)
hc.close();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
return res;
}
The response is like:
{\rtf1\ansi\ansicpg1252\uc1\deflang1033\adeflang1033...................
I can read the data but its not formatted, so that i can read that programetically too.
I have done with this task....
Actually the mistake was on server side.
When they were performing OCR, the format parameter was not corrected that was reason.

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

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

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