Im having difficulties with the HttpConnection posting data to my server. The first time everything goes well. The second time it says; 'Stream already open', but i close everything after the response.
Here is my code:
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.location.*;
import java.io.*;
class GetSnowheights
{
HttpConnection http = null;
QualifiedCoordinates q = null;
public String result = "Geen data";
private boolean running;
public GetSnowheights(QualifiedCoordinates q) {
try
{
/*
this.http = (HttpConnection)Connector.open("http://www.diamond4it.nl/bb/");
this.http.setRequestMethod(HttpConnection.POST);
this.http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
*/
//Internet.getInstance();
this.http = Internet.getConnection();
}catch(Exception err){
err.printStackTrace();
}
this.q = q;
this.result = "Running";
}
public void GetResult(){
StringBuffer sb = new StringBuffer();
this.result = "GetResult";
if(this.http != null){
OutputStream os = null;
InputStream is = null;
try
{
//Send request
os = this.http.openOutputStream();
String data = "lat=1&lng=1";
//String data = "lat=" + this.q.getLatitude() + "&lng=" + this.q.getLongitude();
os.write(data.getBytes());
os.flush();
os.close();
this.result = "dataSend";
//Check response and read data
int res = this.http.getResponseCode();
this.result = "Result: " + res;
if(res == 200){
is = this.http.openInputStream();
int ch;
// Check the Content-Length first
long len = this.http.getLength();
if(len!=-1) {
for(int i = 0;i<len;i++){
if((ch = is.read())!= -1){
sb.append((char)ch);
}
}
} else {
// if the content-length is not available
while ((ch = is.read()) != -1){
sb.append((char)ch);
}
}
is.close();
}
this.result = sb.toString();
}catch(Exception err){
//err.printStackTrace();
this.result = err.toString() + "\r\n" + err.getMessage();
}finally{
if(is != null){
try{
is.close();
}catch(Exception err){
err.printStackTrace();
}
}
if(os != null){
try{
//os.flush();
os.close();
}catch(Exception err){
err.printStackTrace();
}
}
/*
if(http != null){
try{
http.close();
}catch(Exception err){
err.printStackTrace();
}
}
*/
}
}else{
this.result = "No connection";
}
}
}
2 ideas:
Why have you commented out the http.close() in finally block? We should always close HttpConnections.
Don't you call GetResult() from several threads simultaneously? If yes, then make the method synchronized by adding synchronized keyword in its definition.
P.S. I find the design of the class a bit misleading. It's very easy to make a mistake by incorrect usage of it. I'd combine GetSnowheights and GetResult into the only synchronized method.
Related
I am using following code for getting contents of a web page
String url = "http://abc.com/qrticket.asp?qrcode="
+ "2554";
try {
url += ";deviceside=true;interface=wifi;ConnectionTimeout=" + 50000;
HttpConnection connection = (HttpConnection) Connector.open(url,
Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.GET);
// connection.openDataOutputStream();
InputStream is = connection.openDataInputStream();
String res = "";
int chr;
while ((chr = is.read()) != -1) {
res += (char) chr;
}
is.close();
connection.close();
showDialog(parseData(res));
} catch (IOException ex) {
ex.printStackTrace();
showDialog("http: " + ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
showDialog("unknown: " + ex.getMessage());
}
public void showDialog(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(text);
}
});
}
public String parseData(String str) {
String[] data = split(str, "//");
StringBuffer builder = new StringBuffer();
for (int i = 0; i < data.length; i++) {
System.out.println("data:" + data[i]);
String[] vals = split(data[i], ">>");
if (vals.length > 1) {
System.out.println(vals[0]);
builder.append(vals[0].trim()).append(": ")
.append(vals[1].trim()).append("\n");
} else {
builder.delete(0, builder.toString().length()).append(
vals[0].trim());
break;
}
}
return builder.toString();
}
public String[] split(String splitStr, String delimiter) {
// some input validation
if (delimiter == null || delimiter.length() == 0) {
return new String[] { splitStr };
} else if (splitStr == null) {
return new String[0];
}
StringBuffer token = new StringBuffer();
Vector tokens = new Vector();
int delimLength = delimiter.length();
int index = 0;
for (int i = 0; i < splitStr.length();) {
String temp = "";
if (splitStr.length() > index + delimLength) {
temp = splitStr.substring(index, index + delimLength);
} else {
temp = splitStr.substring(index);
}
if (temp.equals(delimiter)) {
index += delimLength;
i += delimLength;
if (token.length() > 0) {
tokens.addElement(token.toString());
}
token.setLength(0);
continue;
} else {
token.append(splitStr.charAt(i));
}
i++;
index++;
}
// don't forget the "tail"...
if (token.length() > 0) {
tokens.addElement(token.toString());
}
// convert the vector into an array
String[] splitArray = new String[tokens.size()];
for (int i = 0; i > splitArray.length; i++) {
splitArray[i] = (String) tokens.elementAt(i);
}
return splitArray;
}
This is working absolutely fine in simulator but giving 'http:null' (IOException) on device, I dont know why??
How to solve this problem?
Thanks in advance
I think the problem might be the extra connection suffixes you're trying to add to your URL.
http://abc.com/qrticket.asp?qrcode=2554;deviceside=true;interface=wifi;ConnectionTimeout=50000
According to this BlackBerry document, the ConnectionTimeout parameter isn't available for Wifi connections.
Also, I think that if you're using Wifi, your suffix should simply be ";interface=wifi".
Take a look at this blog post on making connections on BlackBerry Java, pre OS 5.0. If you only have to support OS 5.0+, I would recommend using the ConnectionFactory class.
So, I would try this with the url:
http://abc.com/qrticket.asp?qrcode=2554;interface=wifi
Note: it's not clear to me whether your extra connection parameters are just ignored, or are actually a problem. But, since you did get an IOException on that line, I would try removing them.
The problem was that no activation of blackberry internet service. After subscription problem is solved.
Thanks alto all of you especially #Nate
I am working on a blackberry application in which I need to hit a url create a connection and write a file and save that to SDcard. Currently I am following this particular code. But while creating FileOutputStream object it throws CLassCastException. I am struggling with this.
public void run() {
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
OutputStream fos=null;
int rc;
try {
httpConnection = new HttpConnectionFactory()
.getHttpConnection("http://faultcode.techvalens.net/PDF/DrawingSample.PDF");
rc = httpConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
httpInput = httpConnection.openInputStream();
InputStream is = httpInput;
FileConnection fconn=(FileConnection)Connector.open("file:///SDCard/Test.txt",
Connector.READ_WRITE);
if(!fconn.exists())
fconn.create();
System.out.println(fconn.exists());
fos = new FileOutputStream( File.FILESYSTEM_PATRIOT, "Test.txt" );
// byte[] b = IOUtilities.streamToBytes(inp);
byte[] buffer = new byte[702];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
} catch (Exception ex) {
System.out.println("URL Error........" + ex.getMessage());
} finally {
try {
if (httpInput != null)
httpInput.close();
if (httpDataOutput != null)
httpDataOutput.close();
if (httpConnection != null)
httpConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
the above code i am using.
Please let me know what is my mistake.
THanx in advance...!!!
The task was basic but created an unforgettable concept for me. Below is the code now i am using, its the best if i need to download any type file from URL.
public void run(){
GetURLWebService _webService = new GetURLWebService(methodName,elecID,pdfType,performedBy,notes);
String pdfURL = _webService.getWebServiceData();
_pdfURL = pdfURL;
System.out.println("Download the pdf...!!!");
try {
int chunkIndex = 0;
int totalSize = 0;
/*
* File connection
*/
FileConnection file =(FileConnection)Connector.open(localFile);
if (!file.exists()) {
file.create();
}
file.setWritable(true);
OutputStream out = file.openOutputStream();
/*
* HTTP Connections
*/
String currentFile = _pdfURL + connectionType();
//log("Full URL: " + currentFile);
HttpConnection conn;
InputStream in;
int rangeStart = 0;
int rangeEnd = 0;
while (true) {
// log("Opening Chunk: " + chunkIndex);
conn = (HttpConnection) Connector.open(currentFile,
Connector.READ_WRITE, true);
rangeStart = chunkIndex * chunksize;
rangeEnd = rangeStart + chunksize - 1;
// log("Requesting Range: " + rangeStart +
// "-" + rangeEnd);
conn.setRequestProperty("Range", "bytes=" +
rangeStart + "-" + rangeEnd);
int responseCode = conn.getResponseCode();
if (responseCode != 200 && responseCode != 206)
{
// log("Response Code = " + conn.getResponseCode());
break;
}
// log("Retreived Range: " + conn.getHeaderField("Content-Range"));
in = conn.openInputStream();
int length = -1;
byte[] readBlock = new byte[256];
int fileSize = 0;
while ((length = in.read(readBlock)) != -1) {
out.write(readBlock, 0, length);
fileSize += length;
Thread.yield(); // Try not to get cut off
}
totalSize += fileSize;
// log("Chunk Downloaded: " + fileSize + " Bytes");
chunkIndex++; // index (range) increase
in.close();
conn.close();
in = null;
conn = null;
/*
* Pause to allow connections to close and other Threads
* to run.
*/
Thread.sleep(1000);
}
// log("Full file downloaded: " + totalSize + " Bytes");
out.close();
file.close();
// log("Wrote file to local storage");
} catch (Exception e) {
System.out.println(e.toString());
}
}
private String connectionType() {
switch (conn) {
case 1:
return ";deviceside=false";
case 2:
return ";deviceside=true;interface=wifi";
default:
return ";deviceside=true";
}
}
I want to get the Bitmap from URL like -
"https://graph.facebook.com/100003506521332/picture"
I tried how-i-can-display-images-from-url-in-blackberry . But its showing http error 302 .It dont showing the Bitmap. How to resolve the problem ?.
String url = "https://graph.facebook.com/100003506521332/picture";
try
{
bitmap = globleDeclaration.getLiveImage(url, 50, 50);
bitmapField.setBitmap(bitmap);
}
catch (IOException e)
{
e.printStackTrace();
Dialog.alert(e.getMessage());
}
public Bitmap getLiveImage(String url,int width,int height) throws IOException
{
Bitmap bitmap = null;
try
{
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
httpconnection = (HttpConnection) Connector.open(url, Connector.READ, true);
String location=httpconnection.getHeaderField("location");
if(location!=null){
httpconnection = (HttpConnection) Connector.open(location, Connector.READ, true);
}else{
httpconnection = (HttpConnection) Connector.open(url, Connector.READ, true);
}
inputStream = httpconnection.openInputStream();
while (-1 != (length = inputStream.read(responseData)))
{
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = httpconnection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
throw new IOException("HTTP response code: "
+ responseCode);
}
final String result = rawResponse.toString();
byte[] dataArray = result.getBytes();
encodeImageBitmap = EncodedImage.createEncodedImage(dataArray, 0, dataArray.length);
}
catch (final Exception ex)
{
System.out.print("Exception (" + ex.getClass() + "): " + ex.getMessage());
}
finally
{
try
{
inputStream.close();
inputStream = null;
httpconnection.close();
httpconnection = null;
}
catch(Exception e){}
}
return bitmap;
}
If you done get responce from this code httpconnection = (HttpConnection) Connector.open(url, Connector.READ, true); which is mention in above answer than u can also use alternative solution for that..
You can pass your your id here http://graph.facebook.com/100003506521332/?fields=picture&type=large than you will get one json responce like that {"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/70678_100003506521332_1415569305_n.jpg"}
parse this json and get which you want exaclty .. than you will get responce using httpconnection = (HttpConnection) Connector.open(url, Connector.READ, true); also .
if you dont want larger image than remove &type=large from the above url.
//YOUR PACKAGE NAME
package ...........;
//*************************
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.system.Bitmap;
public class Util_ImageLoader {
public static Bitmap getImageFromUrl(String url) {
Bitmap bitmap = null;
try {
String bitmapData = getDataFromUrl(url);
bitmap = Bitmap.createBitmapFromBytes(bitmapData.getBytes(), 0,
bitmapData.length(), 1);
} catch (Exception e1) {
e1.printStackTrace();
}
return bitmap;
}
private static String getDataFromUrl(String url) {
StringBuffer b = new StringBuffer();
InputStream is = null;
HttpConnection c = null;
long len = 0;
int ch = 0;
try {
c = (HttpConnection) Connector.open(url);
is = c.openInputStream();
len = c.getLength();
if (len != -1) {
for (int i = 0; i < len; i++)
if ((ch = is.read()) != -1) {
b.append((char) ch);
}
} else {
while ((ch = is.read()) != -1) {
len = is.available();
b.append((char) ch);
}
}
is.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
return b.toString();
}
}
copy this to your package....
Now, to use this class do like this>>>>>>>>
CREATE BITMAP OBJECT:
Bitmap IMAGE;
After That:
IMAGE=Util_ImageLoader.getImageFromUrl("https://graph.facebook.com/100003506521332/picture");
By the way, I think you have missed extension
like JPG,PNG, on your URL.... Check That
Now, add your bitmap where you would like to display the image......
ENJOY!
add(IMAGE);
I tired to connect my app with the remote server and pass few credentials to it, but i am always getting a same response from the server. I tried changing all the parameter value and other request header values that i am passing, but still i can't reach the exact solution. I need to you, whether am i using the correct way to ping with the server and to pass the values.
Below is the code that i am using , Please let me know if i have gone wrong somewhere.
// HttpServiceConnection.java
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.HttpsConnection;
import net.rim.device.api.system.DeviceInfo;
import com.beacon.bb.app.util.WSMConfig;
/**
* #author N********
*
*/
public class HttpServiceCommunication {
public HttpServiceCommunication() {
System.out.println("Http Service Communication Called");
}
public String sendHttpPost(String uri, String email, String uid,
String pass) throws Exception { // Hashtable header
String response = null;
// create the connection...
System.out.println("Url " + uri);
HttpConnection _connection = null;
String params = null;
if (DeviceInfo.isSimulator()) {
params = ";deviceside=false";
} else {
params = ";deviceside=true;interface=wifi";
}
String URL = uri + params;
System.out.println("Connecting to Http Connection ");
try {
_connection = (HttpConnection) Connector.open(URL);
} catch(Exception e){
e.printStackTrace();
}
if (_connection != null) {
_connection.setRequestMethod(HttpConnection.POST);
System.out.println("After Request Method ");
_connection.setRequestProperty("User-Agent",
"Profile/MIDP-2.0 Configuration/CLDC-1.1");
_connection.setRequestProperty("Content-Language", "en-US");
_connection.setRequestProperty("Content-type", "application/json");
// setting header if any
// if (header != null) {
// for (Enumeration en = header.keys(); en.hasMoreElements();) {
// String key = (String) en.nextElement();
// String value = (String) header.get(key);
// _connection.setRequestProperty(key, value);
_connection.setRequestProperty("email", email);
//_connection.setRequestProperty("method","login");
_connection.setRequestProperty("uid", uid);
_connection.setRequestProperty("password", pass);
//_connection.setRequestProperty("uid", uid);
// }
// }
System.out.println("Open Output Stream ");
// System.out.println("Data is "+data);
OutputStream _outputStream = _connection.openOutputStream();
//System.out.println("Writing data ");
//_outputStream.write(data);
// _outputStream.flush(); // Optional, getResponseCode will flush
// Getting the response code will open the connection, send the
// request, and read the HTTP response headers.
// The headers are stored until requested.
try {
System.out.println("Response Code :" + _connection.getResponseCode());
int rc = _connection.getResponseCode();
System.out.println("Response Code :" + rc);
System.out.println("Response Code :" + rc + " if HTTP OK :"
+ (rc == HttpConnection.HTTP_OK));
if (rc == HttpConnection.HTTP_FORBIDDEN) {
System.out.println("FORBIDDEN");
response = WSMConfig.NOT_AUTH;
} else if (rc != HttpConnection.HTTP_OK) {
response = WSMConfig.NOT_OK;
} else if (rc == HttpConnection.HTTP_OK) {
InputStream _inputStream = _connection.openInputStream();
final int MAX_LENGTH = 128;
byte[] buf = new byte[MAX_LENGTH];
int total = 0;
while (total < MAX_LENGTH) {
int count = _inputStream.read(buf, total, MAX_LENGTH
- total);
if (count < 0) {
break;
}
total += count;
}
response = new String(buf, 0, total);
//ByteBuffer bb = new ByteBuffer(_inputStream);
//response = bb.getString();
System.out.println("Response from Server :" + response);
// close everything out
{
if (_inputStream != null)
try {
_inputStream.close();
} catch (Exception e) {
}
if (_outputStream != null)
try {
_outputStream.close();
} catch (Exception e) {
}
if (_connection != null)
try {
_connection.close();
} catch (Exception e) {
}
}
}
else {
response = WSMConfig.SERVER_ERROR;
}
}catch(Exception e){
e.printStackTrace();
}
}
//System.out.println("Response :" + response);
return response;
}
}
I am getting a response like {"code":0,"err":"Missing 'method'."}
Any Help is Appreciable....
Thanks
Try this out when you're wanting to pass data to the server:
//encode your data to send
URLEncodedPostData encoder = new URLEncodedPostData(null, false);
encoder.encode("email", email);
encoder.encode("method", "login");
encoder.encode("uid", uid);
encoder.encode("password", pass);
//Now you open up an output stream to write to the connection
OutputStream os = _connection.openOutputStream();
os.write(encoder.getBytes();
os.flush();
And then continue with the rest of your logic
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;
}