Connection being made, but content is unable to be retrieved from web service - blackberry

public class ConsumeFactoryThread extends Thread {
private String url;
private HttpConnection httpConn;
private InputStream is;
private CustomMainScreen m;
private JSONArray array;
public ConsumeFactoryThread(String url, CustomMainScreen m){
System.out.println("Connection begin!");
this.url = url;
this.m = m;
}
public void finished(){
m.onFinish(array);
}
public void run(){
myConnectionFactory connFact = new myConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
System.out.println("Connection factory!");
if(connDesc != null)
{
System.out.println("Connection not null!");
httpConn = (HttpConnection) connDesc.getConnection();
is = null;
try
{
final int iResponseCode = httpConn.getResponseCode();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
System.out.println("Connection in run!");
// Get InputConnection and read the server's response
InputConnection inputConn = (InputConnection) httpConn;
try {
is = inputConn.openInputStream();
System.out.println("Connection got inputstream!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = null;
try {
data = IOUtilities.streamToBytes(is);
System.out.println("Connection got data!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String result = new String(data);
System.out.println("Connection Data: "+result);
try {
array = new JSONArray(result);
//finished();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
catch(IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
}
}
I'm using the blackberry torch 9800 simulator and hardware device for testing.
In the simulator I cannot retrieve the data over wifi, even though the connection to wifi is found. It works when the mobile network is enabled.
Now, when I replace my web service with the Twitter api, I get the data regardless of transport type. I tried adding ;deviceside=false to my url, but nothing. It's not https or anything.
I just want my web service accessed! I know nothing about this mds,bis,bes,bis_b junk.
EDIT:
Jeez. I'm realizing it may be my site. Not using the web service and just retrieving the page, www.example.com, I get nothing. But, google.com or any other site I use retrieves the html. Am I missing headers!?!

Try appending ;interface=wifi to the end of your URL, this will force the simulator to use your simulated Wi-Fi connection, which is your PC's network connection.
You will need to have setup Wi-Fi on the simulator by going to Manage Connections->Set Up Wi-Fi Network, then connect to Default WLAN Network.

Related

Try to connect to MQTT Server with a Broadcast Receiver when WiFi is connected (Paho)

I have a Broadcast receiver that checks WIFI_STATE_CHANGE to see if I have connected to a certain WiFi network. For example if I am coming home, I want a certain MQTT message to be sent. The problem I have is that it connects and sends the MQTT message, only when run the app the first time.
Process:
If I build the application and run it on the device and it recognised my home WiFi it sends the message.
I turn off Wifi from the device, and turn it back on again.
I get "Failure" which is a message when the MQTT connection to the server could not be established.
What I would need is that after I reconnect to the network, instead of "Failure" to get "Connected" but somehow it never happens...what could be wrong?
PS. I think it has to do with the fact that when WiFi is detected, the Broadcast Receiver runs the connection code, although Internet is not available at that point of time (obtaining IP etc.)
Here is the code of the Broadcast receiver:
package me.app.comehomedemo;
import ...
public class SynchronizeBroadcastReceiver extends BroadcastReceiver {
MqttAndroidClient client;
static String MQTTHOST = "myhost";
static String USERNAME = "myusername";
static String PASSWORD = "mypassword";
static String topicStr = "/topic/mac/control";
static String payload = "1";
#Override
public void onReceive(final Context context, Intent intent) {
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (info.isConnected()) {
WifiManager wifiManager = ( WifiManager ) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
Toast.makeText(context, String.valueOf(ip), Toast.LENGTH_SHORT).show();
String ssid = wifiInfo.getSSID();
if (ssid.equals("\"mySSID\"")) {
String clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(context.getApplicationContext(), MQTTHOST, clientId);
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(USERNAME);
options.setPassword(PASSWORD.toCharArray());
// options.setAutomaticReconnect(true);
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();
try {
client.publish(topicStr, payload.getBytes(), 0, false);
} catch (MqttException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Toast.makeText(context, "Failure", Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer mp = MediaPlayer.create(context.getApplicationContext(), notification);
mp.start();
}
}
}
}
I have managed to solve it by waiting 2 seconds and then running the task. Used this solution and it worked. I had to wait for the Internet connection to get ready!
Since waiting 2 seconds has solved your problem, then it might be that the Wifi broadcast comes too early, before there is a connection established (like DHCP gives your phone IP and establishes the routes) for the MQTT connect and publish packets to be properly delivered.
But what happens if some other user needs to wait 10 and not 2 seconds?
My suggestion is to set the automatic reconnect option in MqttConnectOptions and then use the connection callback to publish the needed info to the broker and finally disconnect in publish callback:
private IMqttActionListener mConnectCallback = new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken token) {
try {
client.publish(topicStr, new MqttMessage(payload.getBytes()), null, mPublishCallback);
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken token, Throwable ex) {
}
};
private IMqttActionListener mPublishCallback = new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken token) {
// TODO disconnect
}
#Override
public void onFailure(IMqttToken token, Throwable ex) {
}
};
MqttAndroidClient client = new MqttAndroidClient(context, MQTTHOST, "my_id");
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(USERNAME);
options.setPassword(PASSWORD.toCharArray());
options.setAutomaticReconnect(true);
client.connect(options, null, mConnectCallback);

c# server and android client,connectivity

i am trying to develop an application in c# which acts as a server for an android phone.i am using 32feet.net for bluetooth in c# and i have a server running in android, which simply sends a socket to server. the server running in pc need to listen the connection and display ,the status of connection. all these things are base for my project. the server code is as shown :
namespace testserver
{
class Program
{
static void Main(string[] args)
{
BluetoothClient bc = new BluetoothClient();
BluetoothDeviceInfo[] dev;
BluetoothDeviceInfo td=null;
Guid id = new Guid("{00112233-4455-6677-8899-aabbccddeeff}");
// Console.WriteLine(id.ToString());
// Console.Read();
dev = bc.DiscoverDevices();
foreach (BluetoothDeviceInfo d in dev)
{
if (d.DeviceName == "ST21i")//my phone name
{
td=d;
break;
}
}
try
{
BluetoothAddress addr = td.DeviceAddress;
BluetoothListener bl = new BluetoothListener(addr, id);
bl.Start();
if (bl.AcceptSocket() != null)
Console.WriteLine("Success");
}
catch (Exception e)
{
Console.WriteLine("Exception : "+e.Message);
Console.Read();
}
}
}
}
and here is my android code :
public class MainActivity extends Activity {
BluetoothAdapter adapter;
BluetoothDevice bd;
BluetoothSocket sock;
OutputStream ostr;
int REQUEST_ENABLE_BT;
String str="5C:AC:4C:DD:CC:0D";
private static final UUID id=UUID.fromString("00112233-4455-6677-8899- aabbccddeeff");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter=BluetoothAdapter.getDefaultAdapter();
if (!adapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "clicked button", Toast.LENGTH_LONG).show();
try
{
bd=adapter.getRemoteDevice(str); Toast.makeText(getApplicationContext(),"Server is running at "+bd.getName().toString()+"...", Toast.LENGTH_LONG).show();
sock=bd.createInsecureRfcommSocketToServiceRecord(id); sock.connect();
ostr=sock.getOutputStream();
ostr.write(0);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}
my problems are :
1) in pc i am getting an exception, the requested address is not valid in its context(so that server cant run )
2)in phone, the service discovery failed( because of unavailability of server)
how can i correct the server and run the program ?
i changed the bluetooth listener object's creation from
BluetoothListener bl = new BluetoothListener(addr, id); to
BluetoothListener bl = new BluetoothListener(id); and everything worked fine..

Unable to connect BlackBerry phone with Bluetooth SPP device

I am trying to connect to a bluetooth device from the blackberry 9900 phone using the following code;
public final class AppMainScreen extends MainScreen {
private BluetoothspInfo[] spInfo;
private StreamConnection bConn;
private DataInputStream diStream;
private String text;
public AppMainScreen() {
spInfo = BluetoothSerialPort.getSerialPortInfo();
try {
bConn = (StreamConnection) Connector.open(
spInfo[0].toString(), Connector.READ);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
UiApplication.getUiApplication().invokeLater(new TextScanner());
}
// ...
// ...
// ...
}
But its always throwing the exception java.io.IOException: Unable to connect. I am not able to get the full trace.
What is the problem here, can anybody please point me in the right direction.
I am using the BlackBerry Java on BlackBerry Eclipse Plugin with Platform version 4.5.

Blackberry Java - Fixed length streaming a POST body over a HTTP connect

I'm working on some code which POSTs large packets often over HTTP to a REST server on IIS. I'm using the RIM/JavaME HTTPConnection class.
As far as I can tell HTTPConnection uses an internal buffer to "gather" up the output stream before sending the entire contents to the server. I'm not surprised, since this is how HttpURLConnect works by default as well. (I assume it does this so that the content-length is set correctly.) But in JavaSE I could override this behavior by using the method setFixedLengthStreamingMode so that when I call flush on the output stream it would send that "chunk" of the stream. On a phone this extra buffering is too expensive in terms of memory.
In Blackberry Java is there a way to do fixed-length streaming on a HTTP request, when you know the content-length in advance?
So, I never found a way to do this was the base API for HTTPConnection. So instead, I created a socket and wrapped it with my own simple HTTPClient, which did support chunking.
Below is the prototype I used and tested on BB7.0.
package mypackage;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
public class MySimpleHTTPClient{
SocketConnection sc;
String HttpHeader;
OutputStreamWriter outWriter;
InputStreamReader inReader;
public void init(
String Host,
String port,
String path,
int ContentLength,
String ContentType ) throws IllegalArgumentException, IOException
{
String _host = (new StringBuffer())
.append("socket://")
.append(Host)
.append(":")
.append(port).toString();
sc = (SocketConnection)Connector.open(_host );
sc.setSocketOption(SocketConnection.LINGER, 5);
StringBuffer _header = new StringBuffer();
//Setup the HTTP Header.
_header.append("POST ").append(path).append(" HTTP/1.1\r\n");
_header.append("Host: ").append(Host).append("\r\n");
_header.append("Content-Length: ").append(ContentLength).append("\r\n");
_header.append("Content-Type: ").append(ContentType).append("\r\n");
_header.append("Connection: Close\r\n\r\n");
HttpHeader = _header.toString();
}
public void openOutputStream() throws IOException{
if(outWriter != null)
return;
outWriter = new OutputStreamWriter(sc.openOutputStream());
outWriter.write( HttpHeader, 0 , HttpHeader.length() );
}
public void openInputStream() throws IOException{
if(inReader != null)
return;
inReader = new InputStreamReader(sc.openDataInputStream());
}
public void writeChunkToServer(String Chunk) throws Exception{
if(outWriter == null){
try {
openOutputStream();
} catch (IOException e) {e.printStackTrace();}
}
outWriter.write(Chunk, 0, Chunk.length());
}
public String readFromServer() throws IOException {
if(inReader == null){
try {
openInputStream();
} catch (IOException e) {e.printStackTrace();}
}
StringBuffer sb = new StringBuffer();
int data = inReader.read();
//Note :: This will also read the HTTP headers..
// If you need to parse the headers, tokenize on \r\n for each
// header, the header section is done when you see \r\n\r\n
while(data != -1){
sb.append( (char)data );
data = inReader.read();
}
return sb.toString();
}
public void close(){
if(outWriter != null){
try {
outWriter.close();
} catch (IOException e) {}
}
if(inReader != null){
try {
inReader.close();
} catch (IOException e) {}
}
if(sc != null){
try {
sc.close();
} catch (IOException e) {}
}
}
}
Here is example usage for it:
MySimpleHTTPClient myConn = new MySimpleHTTPClient() ;
String chunk1 = "ID=foo&data1=1234567890&chunk1=0|";
String chunk2 = "ID=foo2&data2=123444344&chunk1=1";
try {
myConn.init(
"pdxsniffe02.webtrends.corp",
"80",
"TableAdd/234234234443?debug=1",
chunk1.length() + chunk2.length(),
"application/x-www-form-urlencoded"
);
myConn.writeChunkToServer(chunk1);
//The frist chunk is already on it's way.
myConn.writeChunkToServer(chunk2);
System.out.println( myConn.readFromServer() );
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
myConn.close();
}

send sms from background thread in blackberry using j2me

hey i made a lot of search and found some similar types of code.
I tried for gsm
method 1 gives IllegalArgumentException
try
{
MessageConnection _mc = (MessageConnection)Connector.open("sms://");
TextMessage tm = (TextMessage) _mc.newMessage(MessageConnection.TEXT_MESSAGE);
tm.setPayloadText(smsText);
tm.setAddress("965xxxxxxx");
_mc.send(tm);
_mc.close();
}catch(exception e){}
method 2: gives java.lang.error exception
try
{
MessageConnection _mc = (MessageConnection)Connector.open("sms://");
TextMessage tm = (TextMessage) _mc.newMessage(MessageConnection.TEXT_MESSAGE,
"//9790XXXXXX");
tm.setPayloadText(text);
_mc.send(tm);
_mc.close();
}catch(Exception e){}
I think the problem is with address
i also tried : but no success
+91965xxxxxxx ,
0091965xxxxxxx ,
0965xxxxxxx
How my application works----
i have created 2 applications--
1) Application 1 is a background app that is a System module as well as
startup application.
2) Another is a uiapplication
the background app runs in background.If there comes an incoming call then a flag value is set in persistent object and after checking that value as true the sms is send to that no from whom call is made.
ok try this
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;
import net.rim.device.api.system.RadioInfo;
public class SendSMS extends Thread {
private String to;
private String msg;
public SendSMS(String to, String msg) {
this.to = to;
this.msg = msg;
}
public void run() {
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + to);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
dc.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
} else {
MessageConnection mc = null;
try {
mc = (MessageConnection) Connector
.open("sms://" + to);
TextMessage m = (TextMessage) mc
.newMessage(MessageConnection.TEXT_MESSAGE);
m.setPayloadText(msg);
mc.send(m);
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
mc.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
}
and call like this
public void callDisconnected(int callId) {
final PhoneCall call = Phone.getCall(callId);
final String number = call.getDisplayPhoneNumber();
SendSMS sendSMS = new SendSMS(number, "message");
sendSMS.start();
super.callDisconnected(callId);
}

Resources