Connecting To a URL through java in Blackberry - java

I am trying to connect to a URL through a Java program in Blackberry simulator. But it is not connecting.
try {
HttpConnection httpConn;
StreamConnection s;
s = (StreamConnection)Connector.open("http://www.google.com/");
httpConn = (HttpConnection)s;
status = httpConn.getResponseCode();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int t=0;
if (status == HttpConnection.HTTP_OK)
{
add(new RichTextField("Successfully Authorized", Field.NON_FOCUSABLE));
}

s = (StreamConnection)Connector.open("http://www.google.com"+";deviceside=true");
try with this line...
If you are trying in emulator means use deviceside=true
If its in a mobile means for wifi connection you have to use interface=wifi

Related

How to check if server connection exists?

In my app I have asyncTask classes, that connects to a local/remote server to get some data, I want to check the server connection before the asyncTask runs,
I have this function:
public static boolean checkServerAvailable(String hostURL) {
HttpURLConnection connection = null;
try {
URL u = new URL(hostURL);
connection = (HttpURLConnection) u.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("HEAD");
int code = connection.getResponseCode();
System.out.println("" + code);
return true;
// You can determine on HTTP return code received. 200 is success.
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
This function uses timeout to connect to server, and if the timeout expires it means that there is no server. The problem is that I'm run this code and it's returning "there is no server" even if the server exists.
I've tried to set a big timeout like 5000ms but it pauses the UI very long time, and sometimes still returns "there is no server" even when the server is exist.
what can I do?
Thank you!
check the server connection before the asyncTask runs
Then you have to do that in another AsyncTask.
So this all makes little sense.
You are not using StrictMode is it?
try using socket here is example code
Socket socket;
final String host = "your.server.IP.or.host";
final int port = 80;
final int timeout = 5000; // 5 seconds or what ever time you want
try {
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), timeout);
}
catch (UnknownHostException uhe) {
Log.e("ServerSock", "I couldn't resolve the host you've provided!");
}
catch (SocketTimeoutException ste) {
Log.e("ServerSock", "After a reasonable amount of time, I'm not able to connect, Server is probably down!");
}
catch (IOException ioe) {
Log.e("ServerSock", "Hmmm... Sudden disconnection, probably you should start again!");
}

Google glass and sockets

I'm trying to connect my Glass with Arduino and a Wifi Shield.
At MenuActivity.java I call (and others methods... but this is the call) :
protected void onCreate(Bundle savedInstanceState)
{
new ConnexioArduino().execute();
super.onCreate(savedInstanceState);
}
And my ConnexioArduino.java :
private boolean socketReady;
private BufferedWriter outA;
private BufferedReader inA;
private Socket mySocket;
....
....
#Override
protected Void doInBackground(Void... params) {
socketReady = true;
String Host = "192.168.43.177";
int Port = 10001;
outA = null;
inA = null;
mySocket = null;
try {
mySocket = new Socket(Host, Port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mySocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
So it only does a connexion between Glass-Arduino Wifi Shield through Socket. But when I execute my app it stops and it gives me the following error : (see image on this link, sorry for the URL I don't have the enough reputation)
http://google-glass-api.googlecode.com/issues/attachment?aid=4630000000&name=Captura+de+pantalla+2014-04-09+a+la%28s%29+13.08.12.png&token=CyuXI9n0-00D4I0inCvN122h42g%3A1398618521508&inline=1
Share your manifest, it should have:
<uses-permission android:name="android.permission.INTERNET"/>
If not you will get a socket failed:eacces (permission denied) error if you step-debug.
Another possible problem is that your server is not accepting the socket request for any number of reasons.
I was able to use your exact code, set up a basic node server on a laptop, and open and close the socket without a crash.
Socket code on Glass should be just like Android according to this:
https://code.google.com/p/google-glass-api/issues/detail?id=272
If you continue to have issues log out the value of e in the exceptions you are catching and paste the result into your question.

How to set a custom variable in HTTP header while POSTing a request

I want to add my Machine Name to the http request header as a custom
variable in JAVA .
Here is my code :
private void sendIssuesToWebService(Issue issue) {
// TODO Auto-generated method stub
System.out.println("\n\n");
//LOG.info("Sending issue : "+issue.getKey());
HttpURLConnection ycSend = null;
BufferedReader in1 = null;
JSONObject j = null ;
try{
URL urlSend = null;
try{
urlSend = new URL(targetURL+"Issue/ImportIssue");
}
catch (MalformedURLException e) {
// TODO Auto-generated catch block
LOG.severe(" URL Malformed Exception while authentication ");
e.printStackTrace();
}
try{
ycSend = (HttpURLConnection) urlSend.openConnection();
}
catch (IOException e) {
// TODO Auto-generated catch block
LOG.severe(" Error in Http URL Connection while authentication");
e.printStackTrace();
}
ycSend.setDoOutput(true);
ycSend.setRequestMethod("POST");
ycSend.setRequestProperty("Content-Type", "application/json");
try{
OutputStreamWriter outSend = null;
outSend = new OutputStreamWriter(ycSend.getOutputStream());
outSend.write(IssueAndHistoryJsonStr);
outSend.flush();
}catch(Exception e)
{
LOG.severe("Cannot write output stream while sending issue ");
}
System.out.println( ycSend.getResponseCode()+"\n\n\n");
if(ycSend.getResponseCode()!=200){
in1 = new BufferedReader(new InputStreamReader(
ycSend.getErrorStream()));
String inputLine;
while ((inputLine = in1.readLine()) != null)
inputResponse=inputResponse+inputLine;
//System.out.println("$$$$$$$"+inputResponse);
try{
j = new JSONObject(inputResponse);
LOG.info(j.get("errors").toString());
}
catch(Exception e){
String errorTitle = inputResponse.substring(inputResponse.indexOf("<title>")+7,inputResponse.indexOf("</title>"));
LOG.severe(errorTitle);
}
LOG.severe(" Error in Sending an Issue to the web service and the issue key is "+issue.getKey());
//LOG.severe("Error is : "+j.get("errors"));
}
else
{
LOG.info("Issue "+issue.getKey()+" Sent successfully" );
countIssues++;
System.out.println("\n\n");
}
//LOG.info("Issue ***** " +issue.getKey()+ " sent with response : "+inputResponse);
}
catch(Exception e)
{
LOG.severe(" Error in Sending an Issue to the web service and the issue key is "+issue.getKey());
//LOG.severe(yc.getResponseMessage());
//LOG.severe("Error is : "+j.get("errors"));
e.printStackTrace();
}
}
I believe you just want to add another requestProperty similar to content type.
ycSend.setRequestProperty("Machine-Name", MachineName);
Maybe this will help. Alternatively you can look at Apache HTTPClient for doing this.
For getting the host name you can do:
try {
InetAddress addr = InetAddress.getLocalHost();
// Get hostname
String hostname = addr.getHostName();
} catch (UnknownHostException e) {
//DO SOMETHING
}

HttpConnection through GPRS (Mobile Network)

I tried to make HttpConnection of URL through GPRS (Mobile network) on real device but it doesn't return data, but I the same code working well through wireliess, the code also working well on simulator
My code is
public static String getHttpUTFResponse(String url) {
HttpConnection connection = null;
byte responseData[] = null;
try {
connection = (HttpConnection) new ConnectionFactory()
.getConnection(url).getConnection();
int len = (int) connection.getLength();
System.out.println(len);
if (len != -1) {
responseData = new byte[len];
DataInputStream dis;
dis = new DataInputStream(connection.openInputStream());
dis.readFully(responseData);
dis.close();
}
} catch (IOException e) {
System.out.println("Connection Error");
} finally {
if (connection != null) {
try {
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection = null;
}
}
if (responseData != null) {
try {
return new String(responseData,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
}
Note: the device browser working well and BB service was registered
Thanks to any one
I am moving my comments to these answer:
In Blackberry setting up the connection url for wireless / gprs / 3g / simulator is pretty challenging, please follow the below pointers
For WiFi on device, make sure you have suffixed ";interface=wifi" to the connection url
For GPRS / 3G on device, make sure you have suffixed ";deviceside=false;connectionUID=" for BIS and ";deviceside=false" for BES to the connection URL
More descriptive explanation can be found at:
Need Clarification ---- Http Connection/GPRS
How to configure an IT Policy on the BlackBerry Enterprise Server to allow only the Internet Browser on the BlackBerry smartphone
Internet Connectivity (APN?)
Tag: APN
Different ways to make an HTTP or socket connection
EDIT: Link 5 was useful for OP
try this..
this will help you to detect the simulator, wifi and gprs connection
getWap2Uid();
String url = "your url";
if(DeviceInfo.isSimulator() == true)
{
conn = (StreamConnection) Connector.open(url+ ";deviceside=true");
}
else
{
if (uid != null)
{
//open a WAP 2 connection
conn = (StreamConnection) Connector.open(url + ";deviceside=true;ConnectionUID=" + uid);
}
else
{
//Consider another transport or alternative action.
conn = (StreamConnection) Connector.open(url +";deviceside=true;interface=wifi");
}
}
getWap2Uid function is here
public static String uid ;
static String getWap2Uid() {
ServiceRecord[] records = ServiceBook.getSB().findRecordsByCid("WPTCP");
for (int i = 0; i < records.length; i++)
{
ServiceRecord serviceRecord = records[i];
String recordName = serviceRecord.toString().toUpperCase();
if (serviceRecord.isValid() && !serviceRecord.isDisabled() &&
serviceRecord.getUid() != null && serviceRecord.getUid().length() != 0 &&
recordName.indexOf("WAP2")!=-1)
{
uid = serviceRecord.getUid();
EventLogger.logEvent(EventLogID, new String("getWap2Uid, UID="+uid).getBytes() );
return uid;
}
}
return null;
}

Transfering text data to a web server using Java

I'm trying to write to a text file on my web server using HttpURLConnection.getOutputStream(). I have tried this on two different servers without success.
I have added a FileWriter to test the InputStream, and that file is created on a local directory correctly, but nothing is showing up on the in the web server directory, even with all password protection off.
Any help would be greatly appreciated.
URL url;
try {
url = new URL("http://www.myWebsite.com/myFile.txt");
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
OutputStream in = new BufferedOutputStream(urlConnection.getOutputStream());
InputStream fin1;
try {
fin1 = new FileInputStream(Environment.getExternalStorageDirectory() + "/fileToRead.txt");
FileWriter fWriter = new FileWriter(Environment.getExternalStorageDirectory() + "/fileToWrite.txt");
int data = fin1.read();
while(data != -1) {
fWriter.write(data);
in.write(data);
data = fin1.read();
}
fWriter.flush();
fWriter.close();
fin1.close();
in.flush();
in.close();
} catch (FileNotFoundException e31) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
} catch (IOException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
} catch (MalformedURLException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
You have to call getInputStream() on the urlConnection in order to get the output stream to flush out the socket to the remote server.
See the discussion here: Why do you have to call URLConnection#getInputStream to be able to write out to URLConnection#getOutputStream?
You are catching the IOException (Right after the IOException) but are not doing anything with it. At least print the stack trace.
You can also use Apache's Http Client http://hc.apache.org/httpcomponents-client-ga/index.html
Much easier than getting URLConnection to work.

Categories

Resources