I have a simple app written the connects to web service (restful). The app works fine on the blackberry simulator however I'm having problems using it on a blackberry 9300.
I keep getting the error "java.io.ioexception: tunnel down" when the apps attempts to call the web service.
The service I am calling is a simple HTTP post and I'm trying to run this over WIFI (the WIFI connection is working fine for browsing the internet).
I'm using a connection string of "http://127.0.0.1:8080/test/restws;interface=wifi" with the IP address changed to the actual Ip address of the server I'm calling. I can call the restful web service on this server on my laptop browser fine.
The code Im using is similar to below & works fine on the simulator. The only thing im changing between the simulator and the code on the phone is the connection string (using "interface=wifi" as oppose to "deviceside=true")
Is this a code problem or is it a setting I need to change on the handset? Any ideas on what I need to do to overcome this.
Thanks
StreamConnection s = (StreamConnection) Connector
.open(connectionString);
httpConn = (HttpConnection) s;
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Length", Integer.toString(postData.length()));
OutputStream output = httpConn.openOutputStream();
output.write(postData.getBytes());
output.flush();
output.close();
String response = httpConn.getResponseMessage();
int statusCode = httpConn.getResponseCode();
if (statusCode != HttpConnection.HTTP_OK) {
}
InputStream is = httpConn.openInputStream();
int ret = 0;
while ((ret = is.read(buf)) > 0) {
os.write(buf, 0, ret);
}
result = new String(os.toByteArray());
I had problems in here .After getting HttpConnection everything is the same i guess. Try this:
ConnectionFactory cf = new ConnectionFactory();
ConnectionDescriptor cd = cf.getConnection("YourUrl");
httpConnector = (HttpConnection) cd.getConnection();
httpConnector.setRequestMethod(HttpConnection.POST);
Related
I have the following problem... I am writing a system consisting of a Server side - on my pc and a Client side on my lovely Xperia (a.k.a. an Android phone). The problem is that when I attempt to bind my phone to the pc, through the client app, the logcat says:
failed to connect to /*xxx.xxx.x.xxx (port 2002): connect failed: ETIMEDOUT (Connection timed out)
*here goes my ip address, it starts with 192...
Actually I use a try - catch on the client side, within the try I set the socket but the problem is that the process fails, I guess, to create the socket properly as it goes in the catch block... I am running both devices on my home Wi-Fi hotspot. As I said I use sockets, which probably means that the type of my connection is TCP (? :) ). Please suggest some kind of a solution to this because the more I continue reading in forums (here as well), the more I get confused.
A snipped of my code:
public class ClientSide extends AsyncTask<String, Void, String>{
protected String doInBackground(String... params){
final String SERVER_HOSTNAME = "xxx.xxx.x.xxx";
final int SERVER_PORT = 2002;
BufferedReader mSocketReader;
PrintWriter mSocketWriter;
final String TAG = ClientSide.class.getSimpleName();
String data="";
String outputln = "Me. Android";
try {
Socket socket = new Socket(SERVER_HOSTNAME, SERVER_PORT);
mSocketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
mSocketWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
System.out.println("Connected to server " + SERVER_HOSTNAME + ":" + SERVER_PORT);
//Reads from the socket
data = mSocketReader.readLine();
//Writes to the socket, a.k.a. sends info
mSocketWriter.println(outputln);
mSocketWriter.flush();
} catch (IOException ioe) {
System.err.println("Cannot connect to " + SERVER_HOSTNAME + ":" + SERVER_PORT);
ioe.printStackTrace();
}
return data;
}
Thank you in advance, if you need more info I will do my best to provide it. I am an extreme beginner in the Android dev, sorry for my English.
*Update: The server side app is written in java, too build of 6-7 classes, I don't run all that through Apache or any of these. I don't want to just test my app, I want a real connection over the wi-fi, not through the usb.
try this: open control panel -> Windows Defender firewall -> allow an app or feature through Windows defender firewall (on left) -> check on Apache HTTP server and mysqld for private and public networks
👍👍👍
I would like to send a GET parameter to a server. I really do not need the InputStream (below), but the request is actually sent when I call "getInputStream". The problem is, this code hangs on getInputStream. The timeout does not apply because the connection is actually established (does not time-out).
What do I need to change so that I'm sending a clean GET to the server without hanging?
URL url = new URL("http://localhost:8888/abc?message=abc"); //[edit]
URLConnection uc = url.openConnection();
uc.setRequestProperty("Accept-Charset", "UTF-8");
uc.setConnectTimeout(1000);
InputStream in = uc.getInputStream();
in.close();
In case it matters, I'm testing with netcat -l as the server instead of using an actual web server. None the less, I would like this code to be very fail-safe so it the server can't adversely effect this code.
I basically gave up in using the URLConnection and wrote the code to use a socket instead. I'm still open for improvements, light-weight posting to a web server is very useful.
URL u = new URL("http://localhost:8888/abc?message=abc");
String get = "";
if (u.getPath() != null)
get += u.getPath();
if (u.getQuery() != null)
get += "?" + u.getQuery();
if (u.getRef() != null)
get += "#" + u.getRef();
Socket socket = new Socket();
socket
.connect(new InetSocketAddress(u.getHost(), u.getPort()),
750);
OutputStream out = socket.getOutputStream();
out.write(("GET " + get + "\n\n").getBytes());
out.close();
I am writing a servlet using eclipse that receives POST request from a client that should do some splitting on the received text, access google geolocation api to get some data and display to the user.
On a localhost, this works perfectly fine. On an actual server (tried with Openshift and CloudBees), this doesn't work. I can see the splitting reply but not the reply from google geolocation service. There is always an error logged into the console from google service. However, the same code works perfectly fine on localhost.
After I receive the POST request in the doPost method of the servlet, I am doing the following to access the Google GeoLocation service:
//Attempting to send data to Google Geolocation Service
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL("https://www.googleapis.com/geolocation/v1/geolocate?key=MyAPI");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request with data (output variable has the JSON data)
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (output);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response2 = new StringBuffer();
while((line = rd.readLine()) != null) {
response2.append(line);
response2.append('\r');
}
rd.close();
//Write to Screen using out=response.getWriter();
out.println("Access Point's Location = " + response2.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
Could you tell me why this is happening and how can I make this work? Should I resort to something like AJAX or is there someother work around? I am relatively new to coding and hence, trying to refrain from learning AJAX at this stage. Please let me if there's any other way of getting this to work
Your localhost has your localhost IP as a sending IP. Openshift et al has the Openshift et al IP as a sending IP. So the Google API says "I have only seen that localhost IP twice before, that's fine!", whereas it says "I have seen this Openshift IP millions of times before! NO REPLY FOR YOU!"
I've read a lot posts on the web, but I haven't found solution.
I've developed a BlackBerry App ( SDK 5 ) that's using HttpConnection to get/set data from server.
I tried to connect via Wireless and G2/G3 connection.
In both cases Application works fine for some time and then suddenly internet connection breaks (sometimes in the middle of the loading data from the server).
After that happens Application doesn't work and I also can't go to any web page (in BB Browser). It looks like BB disables internet.
When I try it in BB Browser I get the following message:
Unable to connect to the Internet please try again later. If the
problem persists please contact your service provider
The only way to get the internet back is to go to settings and disable WiFi and then re-Enable it again. After that it works, but again for some time.
It never breaks at the same point.
Here is the code that I'm using to get data from the server:
String urlPath = "http://www.mysite.com/api/?debug=true";
//debug is my variable on the site, it's not necessary
if(DeviceInfo.isSimulator()){
urlPath += ";deviceside=true";
} else {
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
urlPath += ";interface=wifi";
}else{
urlPath += ";deviceside=true";
}
}
HttpConnection httpConn = (HttpConnection) Connector.open( urlPath );
httpConn.setRequestMethod(HttpConnection.POST);
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
httpConn.setRequestProperty("Content-Language", "en-US");
httpConn.setRequestProperty("Connection", "close");
OutputStream os = httpConn.openOutputStream();
os.write(temp1.getBytes());
os.flush();
os.close();
StringBuffer sb = new StringBuffer();
DataInputStream is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1) {
sb.append((char) chr);
}
String response = new String(sb.toString().getBytes(), "UTF-8");
What am I doing wrong?
Is there a way to fix this and keep the connection stable and responsive?
Thanks.
I am writing a small program to send file between Android and PC through bluetooth. I already
read the bluetooth chat example in google android site.
Currently, my version works really well with sending a text message via bluetooth, but when I send some files, around >= 20 KB, it stops working and throwing EOFException as below:
java.io.EOFException at java.io.ObjectInputStream$BlockDataInputStream.readFully(ObjectInputStream.java:2716)
at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1665)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1340)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1963)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1887)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1770)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1346)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:368)
at com.test.pcserver.BluetoothServerListener.run(BluetoothServerListener.java:74)
at java.lang.Thread.run(Thread.java:636)
Currently, my java program on the PC using bluecove-2.1.0
Here are my main codes:
In Android:
// Get the BLuetoothDevice object
if (BluetoothAdapter.checkBluetoothAddress(address)) {
device = mBtAdapter.getRemoteDevice(address);
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
socket = device .createRfcommSocketToServiceRecord(ProgramConstants.BLUETOOTH_UUID);
socket.connect();
out = new ObjectOutputStream(socket.getOutputStream());
// Send it to PC
out.writeObject(contentObject);
out.flush();
}
In My PC, I read it:
PC Version, server
StreamConnectionNotifier streamConnNotifier = null;
// Create the service url
String connectionString = "btspp://localhost:" + ProgramConstants.BLUETOOTH_UUID.toString()
+ ";name=myappname";
// open server url
streamConnNotifier = (StreamConnectionNotifier) Connector.open(connectionString);
while (true) {
// Wait for client connection
StreamConnection connection = streamConnNotifier.acceptAndOpen();
ObjectInputStream in = new ObjectInputStream(connection.openInputStream());
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
// read string from spp client
DataInController data = new DataInController(model);
data.processDataIn(in.readObject(), dev.getBluetoothAddress());
}
You need to add after flushing the outputstream
out.close();
otherwise the stream can become corrupted.