sending json data to server in blackberry - blackberry

In my application i have to integrate API. I am not getting code for how to check whether internet is available or not. How to send JSON Data to server. Please help me out. As in android we call API in AsyncTask class. In blackberry i did not found like this.
Suggest me some link or ideas so that i can integrate code. I am googling. But did not getting result .
What I have tried is here:
JSONObject postData = new JSONObject();
postData.put("userId", "24");
postData.put("messageTime","06:00:00");
postData.put("language", language[lang_Ocf.getSelectedIndex()]);
System.out.println("********json********"+postData);
ConnectionFactory conFactory = new ConnectionFactory();
ConnectionDescriptor conDesc = null;
try
{
conDesc = conFactory.getConnection(url+";deviceside=true");
}
catch(Exception e)
{
System.out.println(e.toString()+":"+e.getMessage());
}
String response = ""; // this variable used for the server response
// if we can get the connection descriptor from ConnectionFactory
if(null != conDesc)
{
try
{
HttpConnection connection = (HttpConnection)conDesc.getConnection();
//set the header property
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Length", Integer.toString(postData.length()));
connection.setRequestProperty("Content-Type","application/json");
OutputStream out = connection.openOutputStream();
out.write(postData.get);
out.flush();
out.close();
int responseCode = connection.getResponseCode();
if(responseCode == HttpConnection.HTTP_OK){
InputStream in = connection.openInputStream();
StringBuffer buf = new StringBuffer();
int read = -1;
while((read = in.read())!= -1)
buf.append((char)read);
response = buf.toString();
}
Dialog.inform(response);
connection.close();
} catch(Exception e) {
}
}
return response;
Thanks

I solved this problem
Error:
Error: Cannot run program "jar": CreateProcess error=2, The system cannot find the file specified Packaging project HelaBibleWhereUR failed (took 10.715 seconds)
I simply put jar.exe that is under java bin folder in the jre bin folder.

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

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

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

how to upload a file

i try to upload a file from client to server
on the client side, i have a file input
on server side i have
private void uploadFile(final FileTransfer fileTransfer) {
String destinationFile = "/home/nat/test.xls";
InputStream fis = null;
FileOutputStream out = null;
byte buf[] = new byte[1024];
int len;
try {
fis = fileTransfer.getInputStream();
out = new FileOutputStream(new File(destinationFile));
while ((len = fis.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
a file is created on the server, but it's empty
when i debug, i can see then fis is not null
any idea?
Here is a code extract of mine:
try {
File fileData = new File(fileTransfer.getFilename());
// Write the content (data) in the file
// Apache Commons IO: (FileUtils)
FileOutputStream fos = FileUtils.openOutputStream(fileData);
// Spring Utils: FileCopyUtils
FileCopyUtils.copy(fileTransfer.getInputStream(), fos);
// Alternative with Apache Commons IO
// FileUtils.copyInputStreamToFile(fileTransfer.getInputStream(), fileData);
// Send the file to a back-end service
myService.persistFile( fileData );
} catch (IOException ioex) {
log.error("Error with io")
}
return fileTransfer.getFilename(); // this is for my javascript callback fn
Apache Commons IO is a good library to use for such manipulations (I use Spring Utils as well). If you do not have a Spring context, use the commented alternative with Apache (check the syntax, it is not verified).

Resources