don't know why, the app when connecting to the SQL Server that is on the same network as the device, I can connect to it without any problems, but now I need to connect from the device over the internet to the SQL Server, isn't working, don't know why. I have a button to test the connection and it will call a method that contains this, the method is on background (AsyncTaskRunner)
try
{
String host, port, dbname, user, password, instance;
host = _editTextHost.getText().toString();
port = _editTextPort.getText().toString();
instance = _editTextInstance.getText().toString();
dbname = _editTextDbName.getText().toString();
user = _editTextUser.getText().toString();
password = _editTextPass.getText().toString();
String driver = "net.sourceforge.jtds.jdbc.Driver";
String conString;
if (TextUtils.isEmpty(port))
{
conString = "jdbc:jtds:sqlserver://" + host + ";databaseName=" + dbname + ";instance=" + instance;
}
else
{
conString = "jdbc:jtds:sqlserver://" + host + ":" + port + ";databaseName=" + dbname + ";instance=" + instance;
}
Connection con;
Class.forName(driver);
con = DriverManager.getConnection(conString, user, password);
con.close();
conSuccess = true;
}
catch (Exception e)
{
e.printStackTrace();
Log.e("SQLConfig", "Fail to connect");
Log.e("SQLConfig", e.toString());
Log.e("SQLConfig", e.getMessage());
}
return null;
When I do try to connect to the SQL Server on the same network works without any problems, but when I activate the 4g on the device I allways get the same error, that it can't find the instance. But if I connect to the server through the "SQL Server Management Studio" using the same information I can connect to the server without any problems.
I'm using the jtds driver, 1.3.1.
What could be doing this? Thanks
P.S. I all rdy have read some stuff about webservice, but I want to remove this option for now out of the picture
Edit 1: To clarify, I can connect to the server using the credentials on the version of Windows CE of the program or SQL Server Management Studio. When I put the outside IP and all the require information it connects to the server, it not connect on the Android only
Well by changing the conString a little I was able to connect without any problems either from the localnetwork or the internet.
if (TextUtils.isEmpty(port))
{
conString = "jdbc:jtds:sqlserver://" + host + ";databaseName=" + dbname + ";instance=" + instance;
}
else
{
conString = "jdbc:jtds:sqlserver://" + host + ":" + port + ";databaseName=" + dbname + ";instance=" + instance;
}
To
if (TextUtils.isEmpty(port))
{
conString = "jdbc:jtds:sqlserver://" + host + "/" + instance + ";DatabaseName=" +dbname;
}
else
{
conString = "jdbc:jtds:sqlserver://" + host + ":" + port + "/" + instance + ";DatabaseName=" + dbname;
}
Now works without any problems either using the public host or the localnetwork to access the db.
Related
I want to send some files to an FTP server from Android. I have the server IP address, username, and password. I tried to connect to it from Filezilla and it works, however, if I try to connect from Android it fails. I get status code 530 from ftpClient.getReplyCode().
According to https://en.wikipedia.org/wiki/List_of_FTP_server_return_codes the status code means that the login didn't work. ftpClient.login returns false.
So I tried mounting an FTP server with node.js and could connect and upload files perfectly. Then I tried to connect to another test server ftp://test.rebex.net/ using username: demo and password: password and the login works too (uploading files fails because its a test account).
But why do I fail to log in to that specific server from Android but not from Filezilla?
My code:
uploading_to_local_server = true;
FTPClient ftpClient = new FTPClient();
try {
if(port == 0){
ftpClient.connect(ftpserver);
}else {
ftpClient.connect(ftpserver, port);
}
ftpClient.setSoTimeout(10000);
ftpClient.enterLocalPassiveMode();
Log.d(TAG,"FTP. TRYING TO LOGIN ");
Boolean login_response = ftpClient.login(ftp_usr,ftp_psw);
mreplyCode = ftpClient.getReplyCode();
Log.d(TAG,"FTP. RESPONSE " + mreplyCode);
if (login_response) {
Log.d(TAG, "FTP. VIDEOS TO UPLOAD: LOGGED SUCCESFULLY");
//Logged.
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
//iterating through the videos
String video_upload_result = "Uknown Error";
ArrayList<HashMap<String, String>> list_videos_to_upload = dataBaseHelper.getVideosLocalserverH();
for (int counter = 0; counter < list_videos_to_upload.size(); counter++) {
video_upload_result = "Uknown Error";
//list_videos_to_upload.get(counter).put("imei", IMEI);
String video_path = list_videos_to_upload.get(counter).get("dir_route");
String video_name = list_videos_to_upload.get(counter).get("video_name");
String vid_id = list_videos_to_upload.get(counter).get("id");
String sync_status = list_videos_to_upload.get(counter).get("sync");
Log.d(TAG, "VIDEOS TO UPLOAD: " + video_path + " ID: " + vid_id);
//Log.d(TAG, "WIFI STATUS: " + mWifi.isConnected() + " DATA STATUS: " + wData.isConnected());
video_upload_result = try_upload_video_to_ftpserver(ftpClient, video_name, remote_path, video_path);
Log.d(TAG, "VIDEOS TO UPLOAD: " + video_path + " RESULT: " + video_upload_result);
if(video_upload_result.equals("Succes")) {
Log.d(TAG, "TESTING UPLOAD: VIDEO ID: "+ vid_id);
dataBaseHelper.modVideos_Localserver(Collections.singletonList(vid_id));
}else if(video_upload_result.equals(video_path + ": open failed: ENOENT (No such file or directory)")){
Log.d(TAG, "TESTING UPLOAD: ERROR CATCHED. FILE NOT FOUND: "+ vid_id);
dataBaseHelper.modVideos_Localserver(Collections.singletonList(vid_id));
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
Log.d(TAG, "Error Sleeping thread");
e.printStackTrace();
}
}
}
ftpClient.logout();
ftpClient.disconnect();
}catch (IOException e) {
e.printStackTrace();
}
Log.d(TAG, "UPLOADING LOOP ENDED: ");
uploading_to_local_server = false;
EDIT:
Finally Managed to make it work.
Turns out the server only accepted connections through ftps.
So I changed:
FTPClient ftpClient = new FTPClient();
for
FTPSClient ftpClient = new FTPSClient("TLS", false);
and I managed to connect to the server but still coudn´t upload videos because the server also only accepts encrypted data, so I added:
ftpClient.execPROT("P"); // encrypt data channel
And now I can finally upload videos to that server.
After connect to FTP, and then login to FTP.
If to login is success, then you need to let localPassiveMode:
ftpClient.enterLocalPassiveMode();
Then you can upload file to FTP server.
Thank you
Working on a live chat app on Android using XMPP framework / OpenFire and just transferred to a new cloud server but I’m having some problems with the old Android Users Connecting. New users can log in fine and connect to the OpenFire Server.
With the old user accounts it fails the connection the 1st time, but then the 2nd time it connects. Anyone knows what the issue could be?
Can't figure out what the issue is.
hi if your trying to connect xmpp with openfire then just give ssl permission to XMPPTCPConnectionConfiguration with smack library,
private XMPPTCPConnectionConfiguration buildConfiguration() throws XmppStringprepException {
XMPPTCPConnectionConfiguration.Builder builder =
XMPPTCPConnectionConfiguration.builder();
builder.setHost(Common.HOST);
builder.setPort(PORT);
builder.setCompressionEnabled(false);
builder.setDebuggerEnabled(true);
builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
builder.setSendPresence(true);
if (Build.VERSION.SDK_INT >= 14) {
builder.setKeystoreType("AndroidCAStore");
builder.setKeystorePath(null);
} else {
builder.setKeystoreType("BKS");
String str = System.getProperty("javax.net.ssl.trustStore");
if (str == null) {
str = System.getProperty("java.home") + File.separator + "etc" + File.separator + "security"
+ File.separator + "cacerts.bks";
}
builder.setKeystorePath(str);
}
DomainBareJid serviceName = JidCreate.domainBareFrom(Common.HOST);
builder.setServiceName(serviceName);
return builder.build();
}
and call this when you are connecting with server here is example see
XMPPTCPConnectionConfiguration config = buildConfiguration();
SmackConfiguration.DEBUG = true;
this.connection = new XMPPTCPConnection(config);
this.connection.connect();
for more details visit this example
thanks hope this will help you to solve your problem (Y).
To connect to openfire ( any xmpp server ) from android device using SSL follow this with Smack
// Set key for SSL connection
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
config.setKeystoreType("AndroidCAStore");
config.setKeystorekeyPath(null);
} else {
config.setKeystoreType("BKS");
String keyPath = System.getProperty("javax.net.ssl.trustStore");
if (keyPath == null)
keyPath = System.getProperty("java.home") + File.separator + "etc"
+ File.separator + "security" + File.separator + "certs.bks";
config.setKeystorekeyPath(keyPath);
}
}
// Now set custom SSL to configuration
try {
SSLContext ssl = SSLContext.getInstance("TLS");
ssl.init(null, new TrustManager[]{new TLSUtils.AcceptAllTrustManager()}, null);
ssl.getServerSessionContext().setSessionTimeout(10 * 1000);
config.setCustomSSLContext(ssl);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
config.setSecurityMode(Connectionconfig.SecurityMode.required);
// config is type of XMPPTCPConnectionConfiguration
EDIT: For anyone using the same method as I am (building a Soap.java file and using sockets), stop! Use the kSoap-Android library as it automates pretty much everything and has little to no bugs like this.
I'm creating an android application where you can quicly check your timeroster for the classes in the next week. To do this, I use 2 servers:
The server that hosts the timerosters for every student in HTML form
(I do not manage this server)
The server that hosts my webservice (which I manage). It's a .NET webservice and is finished.
The android device connects to the Webservice-server and sends the function "login" with parameters "username": "usernameX" and "password": "passwordX".
The webservice-server then retrieves the login-page from the timeroster-server with the "username" and "password" fields as post parameters. The timeroster-server will respond with a html-page, that will be parsed by the webservice-server and depending on it's contents, the webservice will respond to the Android device with either "Success" or "AuthenticationFail".
To do this, I use the SOAP-architecture on my Android Device, which sends a SOAP-enveloppe to the webservice. The webservice then creates HttpWebRequest- and HttpWebResponse-objects that retrieve the html-source from the timeroster-server.
This approach has worked for me so far using the Socket-class and I have been able to login to the timeroster-server, using my android device. However, the problem lies with another function.
My webservice supports 2 functions: "login" and "GetList". I can perfectly call the "login"-function from my android and receive a "Success"-string. But when I call the "GetList"-function (that takes 3 parameters: a username, a password and a listType), it returns a 400 Bad Request.
When I send the exact same http-request to the webservice-server with Fiddler, I don't receive a 400 Bad Request error.
Why am I getting a 400 error ONLY when I use my android-device? Is there any way I can fix this?
Images for visualisation:
Login-function (using Android):
Login-function (using Fiddler):
GetList-function (using Android) - ERROR HERE:
GetList-function (using Fiddler):
Code used in Android to send data to socket:
public String sendRequest()
{
String s = "";
Socket socket = null;
try
{
socket = new Socket(Server, Port);
}
catch(Exception ex)
{
return "UnknownClientError";
}
String stringbuffer = "";
try
{
socket.getOutputStream();
boolean flag = true;
PrintWriterSuper printwriter = new PrintWriterSuper(socket.getOutputStream());
Scanner scanner = new Scanner(socket.getInputStream());
int i = 295 + MethodName.length() * 2 + XmlNamespace.length();
for(int j = 0; j < ParamNames.size(); j++)
{
String s1 = (String)ParamNames.elementAt(j);
String s2 = (String)ParamData.elementAt(j);
i += s1.length();
i += s2.length();
}
printwriter.println("POST " + WebServicePath + " HTTP/1.1");
printwriter.println("Host: " + Server);
printwriter.println("Content-Type: text/xml; charset=utf-8");
printwriter.println("Content-Length: " + String.valueOf(i));
if(!SoapAction.equals(""))
printwriter.println("SOAPAction: \"" + SoapAction + "\"");
printwriter.println("Connection: Close");
printwriter.println();
printwriter.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
printwriter.println("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
printwriter.println("<soap:Body>");
printwriter.println("<" + MethodName + " xmlns=\"" + XmlNamespace + "\">");
for(int k = 0; k < ParamNames.size(); k++)
{
String s3 = (String)ParamNames.elementAt(k);
String s5 = (String)ParamData.elementAt(k);
printwriter.println("<" + s3 + ">" + s5 + "</" + s3 + ">");
}
printwriter.println("</" + MethodName + ">");
printwriter.println("</soap:Body>");
printwriter.println("</soap:Envelope>");
printwriter.println();
boolean flag1 = false;
int byte0 = 10;
long l = System.currentTimeMillis();
String s4;
while(scanner.hasNextLine() && !flag1)
{
s4 = scanner.nextLine();
stringbuffer += s4 + "\n";
if(System.currentTimeMillis() - l > (long)(1000 * byte0))
flag1 = true;
}
scanner.close();
if(!flag1)
{
String requestString = printwriter.toString();
String s6 = MethodName + "Result";
int i1 = stringbuffer.toString().indexOf("<" + s6 + ">") + s6.length() + 2;
int j1 = stringbuffer.toString().indexOf("</" + s6 + ">");
s = stringbuffer.substring(i1, j1);
} else
{
s = "Error: timed out by client";
}
try{
socket.close();
}catch(Exception ex){}
}
catch (Exception e) {
s = e.getMessage() + "\n" + e.getStackTrace().toString();
}
return s;
}
I am trying to open input and output streams in android but I'm not sure how to go about this. I have opened a socket connection in J2ME previously by using the following in the server:
scn = (ServerSocketConnection) Connector.open("socket://:5000");
String myAddress = scn.getLocalAddress();
si.setText("My address: " + myAddress);
// Wait for a connection.
sc = (SocketConnection) scn.acceptAndOpen();
//Get address of socket connection
String yourAddress = sc.getAddress();
si.setText("Connected to: " + yourAddress);
is = sc.openInputStream();
os = sc.openOutputStream();
Now I want to put this into android but its not letting me open input and output streams and also I had to change a few things which I'm not sure would work in the same way.
scn = (ServerSocket) Connector.open("socket://:5000");
String myAddress = scn.getLocalAddress();
Connection.setText("My address: " + myAddress);
// Wait for a connection.
Socket sc = scn.accept();
//Get address of socket connection
String yourAddress = sc.getAddress();
Connection.setText("Connected to: " + yourAddress);
is = sc.openInputStream();
os = sc.openOutputStream();
The errors which I am getting in android are with the Connector, getLocalAddress, getAddress and openInput and OutputStreams.
I would appreciate any help on this, as I am having great difficulty setting this up in android.
Thanks
Edit:
I have changed the Android code to this:
ServerSocket scn = new ServerSocket(5554);
InetAddress myAddress = scn.getInetAddress();
Connection.setText("My address: " + myAddress);
// Wait for a connection.
Socket sc = scn.accept();
//Get address of socket connection
InetAddress yourAddress = sc.getInetAddress();
Connection.setText("Connected to: " + yourAddress);
is = sc.openInputStream();
os = sc.openOutputStream();
Which compiles fine but I get an error on:
is = sc.openInputStream();
os = sc.openOutputStream();
Is there another way to open input and output streams in android?
Thanks.
I need to make a mysql connection and get some data back. I can do this in Java using this code
try{
String username;
String password;
username = tf.getText();
password = tf2.getText();
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://188.181.248.30:3306/test","simon","123");
int counter = 0;
try{
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM KUNDER");
// System.out.println("NAVN: " + "\t" + "KREDIT: ");
while (res.next() && counter ==0) {
String i = res.getString("NAVN");
String s = res.getString("KREDIT");
System.out.println(i + "\t\t" + s);
if(username.equals(i)){
//stf3.setText("login true");
// System.out.println("username og navn passer sammen et sted");
if(password.equals(s)){
tf3.setText("login true1");
// System.out.println("pass og navn passer sammen");
counter=10;
}else{
tf3.setText("login fail");
counter =10;
}
}else{
//tf3.setText("login fail");
}
}
con.close();
}
catch (SQLException s){
tf3.setText("sql fail");
System.out.println("SQL code does not execute.");
}
But when I try to do this in Android, I get an error when trying to launch the app saying:
[2011-03-06 00:30:04 - sqlLite] Conversion to Dalvik format failed with error 1
I don't know what to do right now. I been reading around the net, but can't find anything I can get working.
Do not access MySQL from Android via JDBC. Wrap your MySQL database in a Web service, and access the Web service from Android.
You might also want to read: Why is the paradigm of "Direct Database Connection" not welcomed by Android Platform?