Hi,
I have a wget command that I want to implantate in an app. the command looks like this
It's executed in a terminal:
Code:
wget --post-data='loginwe=YOURLOGIN&passwordwe=YOURPASS' \
> --save-cookies=my-cookies.txt --keep-session-cookies \
> https://HOSTNAME?cmd=ACTION
the page information have to be saved in a string that will be searched for information.
Can someone help me with the code that can do this job?
UPDATE!
This is what I have tried to incorporate in my app. but I do not get logged in.
Code:
public String getSaldo(String number, String passy) {
HttpClient client = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("https://HOSTNAME?cmd=ACTION");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("phoneNumber", number));
params.add(new BasicNameValuePair("password", passy));
try {
postRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = client.execute(postRequest, responseHandler);
Is there someone who can see why the httpClient command isn't working?
Why not instead try to leverage org.apache.http.client classes and avoid the messiness of using a shell?
http://developer.android.com/reference/org/apache/http/package-summary.html
If you want to go the shell route, check out:
java.lang.Runtime.getRuntime().exec();
it's fairly easy to see what you're getting at but I just thought I'd mention that implantatet is most definitely not a word. not in english anyway..
Thanks Info Updatet
Related
Can't get rid of this error:
android.database.sqlite.SQLiteException: near "s": syntax error: , while compiling:
Select correct from answers where correct = 'Between the airplane's climb angle and the horizon.'
Obviously, it's finding the single quote in ( airplane's ) and considering that the end of the statement.
I've tried:
correct.replaceAll(" ' ", " ''' "); //replace 1 with 3
correct.replaceAll(" ' ", " '' "); // replace 1 with 2
correct.replaceAll(" ' ", " "); // replace 1 with space
(NOTE: the spaces are NOT in the code, I just did that to make it readable)
I have no idea what's going on, IMO, it should work. Maybe I need to try:
String single = "'"; // single '
String double = "''" // double ''
correct.replaceAll(single, double); // ????
Everything I"ve read about sqlite3 is to replace one with two....
TIA,
Roots
\'
\ is the escape character for most languages
so airplane's would be airplane\'s
Also, are you binding your queries with the "question mark" bind?
I'll try the escape and post back later. There are 1,000 rows in the database and I"m pulling a random subset of that, so it's not that often I get one of those situations.
I'm not sure what you mean by "binding with ?" Isn't that what you use for bind variable unknown at runtime? I know my bind variables and just use it in my dbquery. Please enlighten me...always happy to learn something new
Sample code...answerOne would contain the single quote that's killing me
Code:
Cursor c;
c = myDataBase.rawQuery("Select correct from answers where correct = '" + answerOne + "'", null);
if(c.moveToFirst())
answer = "1";
c.close();
binding with question marks should take care of escaping for you.
Basically the question mark is a place holder for a variable in the query.
What you are doing is manually creating the query string. This is considered bad practice these days especially with regards to security. Mostly because it opens up the DB to a SQL injection attack.
So instead of using the rawQuery just use query and you can put a ? in and android will substitute the value for you, all properly escaped:
Code:
String tableName = "answers";
String selectArgs = "correct=[COLOR="Red"]?[/COLOR]";
// if answerOne is string dont need String.valueOf
String[] selectVals = { String.valueOf ( answerOne ) };
String[] columnsProjection= new String[] {"correct" };
Cursor c = db.query(tableName, columnsProjection, selectArgs,selectVals,null);
So in that code the OS will replace the ? in selectArgs with the values in selectVals
This may seem like more writing at first but once you get in the habit it will be easy, reliable and more secure. It also allows you to bind multiple variables to mutiple question marks. It just binds then in the order it gets them.
so something like this:
Code:
String answerOne= "one";
String selectArgs = "correct=? AND age=? AND smiling=?";
String[] selectVals = { answerOne, "21", "yes" };
Ok, I'll try it. There are about 50 different queries in this program...for some reason I just decided to do a rawQuery on this one. I'll change it to "db.query(table name, new String[] {}....yada, yada).
Because, it just crashed and I decided to come back here and check for a solution.
Thank you very much!!!
Roots
Glad to be of help, just remember to hit the thanks booton ya Rooster
Still getting the error
Example: column is in table as text. Say it's equal to:
The driver's last name
Error comes back as "syntax error near 's' when compiling select correct from answers where correct = 'The driver's last name'
That single quote in driver's is killing my SQL.
Hi All,
Things I am trying to do:
1. Connect to remote system
2. Run perl command and get the output on screen.
Could you please guide me on the process where in I can connect to a remote windows/unix machine and run build commands.
Any examples?
Thanks for your help.
Thanks,
Kino
Hi!
I've made something similar - An App that runs some shell scripts on an Ubuntu server over SSH.
Here are some code snippets, hope this helps you
Code:
JSch jsch = new JSch();
Session session = jsch.getSession([I]'ssh-username'[/I],IP, [I]'ssh-port'[/I]);
session.setPassword(SW); // SW ... password ssh-user (for me it's the same pw, ssh-user = su)
Properties prop = new Properties();
prop.put("StrictHostKeyChecking", "no");
session.setConfig(prop);
session.connect();
Channel channel = session.openChannel("exec");
Code:
if(SU) // If Command should run as SU
{
sudoCommand = "sudo -S -p '' " + command;
}
else
{
sudoCommand = command;
}
((ChannelExec) channel).setCommand(sudoCommand);
((ChannelExec) channel).setPty(true);
channel.connect();
OutputStream out = channel.getOutputStream();
ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
channel.setOutputStream(responseStream);
if(SU)
{
out.write((SW + "\n").getBytes());
out.flush();
}
Thread.sleep(1000);
out.write(("logout" + "\n").getBytes());
out.flush();
Thread.sleep(500);
out.write(("exit" + "\n").getBytes());
out.flush();
out.close();
session.disconnect();
channel.disconnect();
Thank you LinuxForce. Thats helpful. I am trying to work on this.
LinuxForce said:
Hi!
I've made something similar - An App that runs some shell scripts on an Ubuntu server over SSH.
Here are some code snippets, hope this helps you
Click to expand...
Click to collapse
Synopsis:
Have you ever wanted as root apps developer to use your favourite Java codes instead of bash/shell commands?
Have you grown tired of Runtime.getRuntime.exec("su") and ProcessBuilder("su").start()?
I did and still do, that's why I've been searching for a solution for my problem until I found out in AOSP source code that some of *.java files run with root access, tracking the way they execute them with root access led me to make this simple library.
Description:
Cmd library -short for Command- is an open source (licensed under Apache licence V2) that allows you to execute java commands with root access privileges by passing package name, full class name and whether your app is a system app or not in just two lines of codes.
For instance, suppose you want to flash a *.img recovery image, the first thing comes to your mind is this code:
Code:
busybox dd if=/path/to/recovery.img of=/path/to/recoveryPartition
lets say /sdcard/recovery.img is the file path and /dev/block/mmcblk0p12 is the partition (Samsung GALAXY Ace Plus GT-S7500)
Here is how to implement it:
Code:
...
Proccess proc = Runtime.getRuntime().exec("su");
OutputStream stream = proc.getOutputStream();
stream.write("busybox dd if=/sdcard/recovery.img of=/dev/block/mmcblk0p12".getBytes());
stream.flush();
...
Pretty simple isn't it, now suppose you don't know anything about bash codes, what will you do?
Let me answer this question:
1) Learn some bash.
2) Use Cmd library with java codes.
Here is the same implementaion with Cmd library:
Code:
...
JavaRoot root = JavaRoot.newInstance(getPackageName(), RootCommands.class.getName(), false);
root.execute("/sdcard/recovery.img", "/dev/block/mmcblk0p12")
...
And in RootCommands.java file (should not be an inner class):
Code:
package com.bassel.example;
import com.bassel.cmd.Command;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Main extends Command
{
private byte[] buffer;
private File recovery, partition;
private FileInputStream in;
private FileOutputStream out;
//static main method implementation is a must
@Override
public static void main(String[] args)
{
//required to start
new Main().run(args);
}
//the begging just like onCreate
@Override
public void onRun()
{
if(argsCount() < 2) showUsage();
System.out.println(String.format("Flashing %s to %s", getArg(0), getArg(1)));
recovery = new File(nextArg());
partition = new File(nextArg());
buffer = new byte[1024 * 1024];
try
{
in = new FileInputStream(recovery);
out = new FileOutputStream(partition);
while(in.read(buffer) > 0)
{
out.write(buffer);
out.flush();
}
in.close();
out.close();
System.out.println("Flashed successfully!");
}
catch (Exception e)
{e.printStackTrace(System.err);}
}
//called upon calling showUsage()
@Override
public void onShowUsage()
{
System.err.println("Two args are needed!");
}
//called once an exception is caught
@Override
public void onExceptionCaught(Exception exception)
{
exception.printStackTrace(System.err);
}
}
Quite lengthy but sometimes we prefer using Java codes to bash ones, don't we?
Here is another example for listing /data files:
Code:
package com.bassel. example;
import java.io.File;
//Without extending Command.class
public class Main
{
@Override
public static void main(String[] args)
{
String[] files = new File("/data").list();
for(String file : files)
{
System.out.println(file);
}
}
}
Usage in depth:
Check root access:
Cmd.root();
No root:
Cmd.SH.ex(String command, String... args);
Cmd.SH.ex(String[] commands);
Cmd.SH.ex(List commands);
With root access:
Cmd.SU.ex(String command, String... args);
Cmd.SU.ex(String[] commands);
Cmd.SU.ex(List commands);
JavaRoot java = JavaRoot.newInstance(String packageName, String className, boolean isSystemApp);
java.execute(String... args);
java.executeInBackground(String... args);
All previous methods aside of the last one:
java.executeInBackground(String... args);
return an instance of type Output that has the following methods:
Code:
boolean success() //returns true if process exit value = 0 else false
String getString() //returns output in String format
String[] getArray() //returns output in String Array format
List getList() //returns output in String List format
int getExitValue() //returns process exit value
String toString() //returns process status and output in String format
Converting:
String string = ...;
String[] array = ...;
List list = ...;
String s1 = Convert.array2string(array);
String s2 = Convert.list2string(list);
String[] a1 = Convert.list2array(list);
String[] a2 = Convert.string2array(string);
List l1 = Convert.array2list(array);
List l2 = Convert.string2list(string);
Library GitHub link:
Cmd (licensed under Apache License, Version 2.0)
Examples:
Window Manipulator
Hello!
Sorry for my bad english.
I'm trying to develop an app that send a push notification from device A (android) to device B (android).
How can I make this app?
I can't use GCM/Parse server, 'cause a push notification is sent ONLY from server to device!
I must use a DB that save MY contacts? And then, with a query (?), sent a push notif. to user B (B have downloaded the app, of course!)?
Thanks!
Venus88 said:
I can't use GCM/Parse server,
Click to expand...
Click to collapse
Yes you can, you would just need to create an API that would capture a message sent to the server from device A then send it to device B.
Jonny said:
Yes you can, you would just need to create an API that would capture a message sent to the server from device A then send it to device B.
Click to expand...
Click to collapse
Thanks a lot!
And how I can do that? The code for GCM server, i.e. gcm.php:
PHP:
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>
and
PHP:
<?php
// response json
$json = array();
/**
* Registering a user device
* Store reg id in users table
*/
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["regId"])) {
$name = $_POST["name"];
$email = $_POST["email"];
$gcm_regid = $_POST["regId"]; // GCM Registration ID
// Store user details in db
include_once './db_functions.php';
include_once './GCM.php';
$db = new DB_Functions();
$gcm = new GCM();
$res = $db->storeUser($name, $email, $gcm_regid);
$registatoin_ids = array($gcm_regid);
$message = array("product" => "shirt");
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
} else {
// user details missing
}
?>
allows send notification from server page to one/a group of devices.
Can i "reverse" the direction? from Device A to server (and then from server to device B) automatically?
Up :\
I'm learning how to manage data that I pull from DB (MYSQL) from this coding. I tried to figure out from free source coding but got stuck on this function, can anybody explain to me flow of this coding?
Code:
protected void onPostExecute(Void aVoid) {
name = names.split(":");
email = emails.split(":");
phone = phones.split(":");
combinedArray = combinedText.split(":");
listView.setAdapter(new ArrayAdapter<String>(RetrieveData.this,
android.R.layout.simple_list_item_1, combinedArray));
progressDialog.dismiss();
}
and when I tried to use this code, red line prompt out and saying that cannot resolved this constructor on if i change
Code:
listItems
to
Code:
names
variables on this
Code:
adapter=new ArrayAdapter<String>(this,
R.layout.list_item, R.id.txtitem, listItems);
I don't understand why I need to use 'split' to pull out the output on listview.