eclipse android pass a java value to php by using HTTP - java

I want to pass the variable q from java to php.
String q = "select author from books where 1";
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www2.XXXX./XXXX/X.php?qy="+q);
//"http://10.0.2.2/tut.php", http://www.XXXX/XXXX/tut.php
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
e.printStackTrace();
System.out.println("Exception 1 caught");
}
However, the php file cannot get the value from java(php connected to mysql correctly).
php coding:
<?php
$con=mysql_connect("XXX.XXX","XX","XXX");
mysql_select_db("XX",$con);
$st = $_GET['qy'];
$r = mysql_query("$st");
while($row=mysql_fetch_array($r))
{
$out[]=$row;
}
print(json_encode($out));
mysql_close($con);
?>
I found that if I just pass the table name to php, it works. But if the passing variable become longer, it went to caught one. How can I fix this? How about passing more than one variable to php (i.e. mysql_query("select $_GET['col'] from $_GET['table'] where $_GET['condition']");)?

Use Post instead of Get, it's more secure.
Something like this:
String col = "author";
String table = "books";
String condition = "1";
try{
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("col", col));
params.add(new BasicNameValuePair("table", table));
params.add(new BasicNameValuePair("condition", condition));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www2.XXXX./XXXX/X.php");
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
e.printStackTrace();
System.out.println("Exception 1 caught");
}
PHP:
<?php
if (isset($_POST['col']) && isset($_POST['table']) && isset($_POST['condition'])){
$columnName= $_POST['col'];
$tableName = $_POST['table'];
$condition = $_POST['condition'];
$dbh=mysql_connect ("localhost", "username", "password") or die('Cannot connect to the database because: ' . mysql_error());
mysql_select_db ("database_name");
$sql=mysql_query("select '$columnName' from '$tableName' where '$condition'");
while($row=mysql_fetch_assoc($sql)) $output[]=$row;
print(json_encode($output));
mysql_close();
}
?>
it works(by mandi yeung)

Never ever send any queries to backend. Your approach is equivalent to an EditText where user can execute desired query on your database. Keep your queries out of your requests at any cost. Query parts (as previous uaer suggested) count too. Query parts from request actually do the same thing.
Sending select query to backend may (and totally will) grant any attacker full access to your database. That means he may change or just delete the data.
I could just tamper your web packet and send drop table statement instead.
drop table authors;
drop table books;
sBetterapproach would be sending json requests like this:
String query = "{
requestedData: getAllBooks,
sessionId: 637euegdifoidhrgeydydihvr
}";
new BasicNameValuePair("smth", query);
Then from your php side you read your input as a plain text $_POST["smth"].
You must then decode your json value into object or array and determine what query you must run.
if ($_GET["smth"]["requestedData"] === "getBooks") {
// get books query executed here
}
Remember: this approach is still not perfect, but it's better than yours

Related

Trouble getting parameters from Android to PHP file for SQL query

I have tried searching about this but could not find any useful answers.
I am attempting to run a query on my database (hosted on a web server) from my Android emulator using eclipse. I can confirm that the correct result of the query is found when I use a constant in the PHP script but when I attempt to pass parameters through it, there is no result. Also, the mysqli does work but I have edited it for this post.
The following is the PHP:
As stated earlier when :name was replaced with a specified string the correct result was returned.
<?php
$con=mysqli_connect("localhost","mylogin","mypass","mydb");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//$username = $_GET['username'];
//$password = $_GET['password'];
$result = mysqli_query($con,"SELECT firstname FROM users WHERE email = ':name'");
$result_params = array(
':name' => $_POST['MyName']
);
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
Here is the Java as well
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(LOGIN_URL);
MyName = MainActivity.getEmail();
try {
// Building Parameters
MyName = MainActivity.getEmail();
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("MyName", MyName));
httppost.setEntity(new UrlEncodedFormEntity(params));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
//response from PHP application
String nameString = response;
welcomename.setText("Welcome " + nameString);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
So to summarise, my question is :What do I need to add to the code to get the parameter 'MyName' from the Java code being posted into the SQL query in the PHP code. I have checked MyName is containing the correct result so the problem I think is on the PHP side.
Thank you very much for your help in advance!
Try passing the parameter like this.
$stmt=$con->prepare('SELECT firstname FROM users WHERE email = ?');
$stmt->bind_param('s', $_POST['MyName'] );
$stmt->execute();
$result = $stmt->get_result();

Curl equivalent POST in java for SOLR

I just started working with SOLR. I want to index some html pages and got this from the documentation:
curl "http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true" -F "myfile=#/home/binaryplease/workspace/SOLRTest/HTMLPages/hello2.html"
Which works as expected as the query returns the expecteed results.
How would I do this exact POST inside a java application?
I tried this as I dont know how to do it with the HttpClient but it's not working:
String command = "curl \"http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true\" -F \"myfile=#\"" +f.getAbsoluteFile() + "\"";
try {
proc = Runtime.getRuntime().exec(command );
InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();
System.out.println("Inputstream " + getStringFromInputStream(in));
System.out.println("Errorstream " + getStringFromInputStream(err));
} catch (IOException e) {
e.printStackTrace();
}
What would be the correct way to index a html file in SOLR and do a query using java?
I would appreciate an example.
EDIT: I got this now which still isn't working:
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("myfile", "#/home/binaryplease/workspace/SOLRTest/HTMLPages/hello3.html"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
System.out.println("Content " + getStringFromInputStream(instream));
} finally {
instream.close();
}
}
}
What am i doing wrong?
You should be using the SolJ client for accessing Solr from Java, which will likely be much easier for you than going the the HTTP interface:
SolrJ is an API that makes it easy for Java applications to talk to
Solr. SolrJ hides a lot of the details of connecting to Solr and
allows your application to interact with Solr with simple high-level
methods.
The center of SolrJ is the org.apache.solr.client.solrj package, which
contains just five main classes. Begin by creating a SolrServer, which
represents the Solr instance you want to use. Then send SolrRequests
or SolrQuerys and get back SolrResponses.
SolrServer is abstract, so to connect to a remote Solr instance,
you'll actually create an instance of HttpSolrServer, which knows how
to use HTTP to talk to Solr.
https://cwiki.apache.org/confluence/display/solr/Using+SolrJ
The setup is pretty easy:
String urlString = "http://localhost:8983/solr";
SolrServer solr = new HttpSolrServer(urlString);
And so are queries:
SolrQuery parameters = new SolrQuery();
parameters.set("q", mQueryString);
QueryResponse response = solr.query(parameters);
SolrDocumentList list = response.getResults();
Same thing with indexing:
String urlString = "http://localhost:8983/solr";
SolrServer solr = new HttpSolrServer(urlString);
SolrInputDocument document = new SolrInputDocument();
document.addField("id", "552199");
document.addField("name", "Gouda cheese wheel");
document.addField("price", "49.99");
UpdateResponse response = solr.add(document);
// Remember to commit your changes!
solr.commit();

how to pass arguments to GET method in RESTfull webservice

I have to pass UserName and password as arguments into GET method for validation.after processing I need to get response.so how can I pass value into RESTful webservice GET method?
To pass parameters in HTTP GET you should use a ? delimiter. Such as
https://mywebsite.com/user/login?username=bob&password=123
https://mywebsite.com/user/login?paramname1=value1&paramname2=value2
Make sure to always use https with any sensitive data. You may also need to escape/encode both username and password to allow extended ASCII. If you need to support UNICODE you should consider using a POST request.
I think, you should use POST method if you want to do something with user name and password. because when you use GET method, the password would be visible on the URI,
https://samplesite.com/page/login?username=John&password=123
https://sampleste.com/page/login?name1=value1&name2=value2
Instead, you could use POST method to send user name and password values and in that case the URI would like below
https://samplesite.com/page/login
And the values will be sent as,
POST /page/login.asp HTTP/1.1
Host: samplesite.com
name1=value1&name2=value2
And you get below advantages on POST Method for secured transaction with server.
It never cached
Requests will remain in the browser history
Requests cannot be bookmarked
Requests have no restrictions on data length
You can do the following for Login validation,
// Create a new HttpClient and Post Header
String downloadedString= null;
HttpClient httpclient = new DefaultHttpClient();
//for registerhttps://te
HttpPost httppost = new HttpPost("YOUR LOGIN URL");
//add data
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", UserName_Edit.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", userPassword_Edit.getText().toString()));
//add data
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream in = response.getEntity().getContent();
StringBuilder stringbuilder = new StringBuilder();
BufferedReader bfrd = new BufferedReader(new InputStreamReader(in),1024);
String line;
while((line = bfrd.readLine()) != null)
stringbuilder.append(line);
downloadedString = stringbuilder.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("downloadedString:in login:::"+downloadedString);
Use AsyncTask for your authentication and write the above method in the doInBackground().
EDIT
You can follow below tutorials also,
http://sarangasl.blogspot.in/2011/06/android-login-screen-using-httpclient.html
http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
Hope it helps.
Hi you can pass arguments to GET method in RESTfull like :
http://yoururl/<arg1>/<arg2>
eg.
http://yoururl/abc/123

Android App that logs in to HTTPS ASPX page

Just to make things clear, I have virtually no experience in HTTP. This project is very ambitious for me, but I am willing to learn in order to be able to accomplish it. I have done some searching for examples across the net, but I can't seem to find an adequate solution. I am aware of terms like GET and POST and understand the basic way to programmatically interact with a website.
Basically, the company I'm working with has a website with a database of clients that I can login to. For starters, I just want to be able to write an Android app that is able to login to the main page with my Username and Password. The site has a login URL of https://"app.companysite.com"/Security/Login.aspx?ReturnUrl=%2fHome%2fDefault.aspx and has a certificate that is for the following purpose: "Ensures the identity of a remote computer".
Is what I'm doing possible? Eventually I would like to be able to open up a Client page and edit their data and re-submit it, but one step a time.
It would be awesome if you could either point me in the direction of some relevant reading material or source code that could help me accomplish my goal.
Thanks in advance!
I don't know if this helps, but the way I did my logins is just for justification. So What I did (since I am assuming the verification is done through a MySQL database) is to create a php file that just verifies the login username and passwords are correct and print out a "correct" or "Yes" otherwise just a "No" or "invalid". Something like this :
php
//Connects to your Database
$username = $_POST['username'];
$password = $_POST['password'];
//make your mysql query if the username and password are in the database
//if there is a an approval
$approval = 1
//otherwise
$approval = 0
if ($approval > 0) {
echo "correct";
} else {
echo "invalid";
}
?>
Now in Android you could make this request to call this website and return the output like the following :
HttpParams httpParameters = new BasicHttpParams();
//make a timeout for the connections in milliseconds so 4000 = 4 seconds httpParameters.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
int timeoutConnection = 4000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 4000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("your website URL");
// Add your data
String username = "your username";
String password = "your password";
List<NameValuePair> nameValuePairs;
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String lines = "";
String data = null;
ArrayList<String> al = new ArrayList<String>();
while((lines = in.readLine()) != null){
data = lines.toString();
al.add(data);
}
in.close();
//To get the response
if(al.get(0).equals("correct")){
//Your login was successful
}
else {
//Your login was unsuccessful
}
I hope this helped you a bit and pointed you in the right direction.

POST login into a website. java-android

I'm trying to login into a website using java and jsoup. But every time I execute my post request I get an IOExeption. The website is www.seriecanal.com. I would appreciate it if someone could review the html form and tell me if I am creating the name-value pairs correctly and if there are any other obvious mistakes with the login. Here's my code:
public HttpResponse postData()
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://seriecanal.com/index.php?page=member");
try
{
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//Get value of input "Regresa_web" because it changes each time i access the site
String Codigo_Fuente ="";
URL url = new URL("http://seriecanal.com/");
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null)
{
Codigo_Fuente= Codigo_Fuente+line;
}
Document Doc = Jsoup.parse(Codigo_Fuente);
Element Regresa_WEb = Doc.getElementById("regresa_web");
String Valor_Regresa_Web = Regresa_WEb.attr("value");
//create name value pairs of the form
nameValuePairs.add(new BasicNameValuePair("_UserName", "userontheweb"));
nameValuePairs.add(new BasicNameValuePair("_Pwd", "123456789"));
nameValuePairs.add(new BasicNameValuePair("btnLogin", "Ingresar"));
nameValuePairs.add(new BasicNameValuePair("_submit_check", "1"));
nameValuePairs.add(new BasicNameValuePair("remember", "ON"));
nameValuePairs.add(new BasicNameValuePair("regresa_web", Valor_Regresa_Web));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse Response = httpclient.execute(httppost);
return Response;
}
catch (ClientProtocolException e)
{
return null;
}
catch (IOException e)
{
Log.i("ERROR", e.toString());
e.printStackTrace();
return null;
}
}
Stack:
04-21 13:42:04.206: D/dalvikvm(324): GC freed 15163 objects / 721152 bytes in 153ms
04-21 13:42:08.026: I/Resources(324): Loaded time zone names for en_US in 1863ms.
04-21 13:42:23.816: I/global(324): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
04-21 13:42:25.696: D/dalvikvm(324): GC freed 21866 objects / 1346160 bytes in 168ms
If you use fiddler or firebug you can interrogate the actual parameters that get sent. When I did this this is what I saw
_submit_check=1
btnLogin=Ingresar
password=test
remember=ON
username=test
It looks like you are sending the wrong params. The form input names do seem different to the ones being sent e.g. _UserName, but you never know if javascript is bound to the event and there is some additional magic going on there. As a result i always use firebug/fiddler.

Categories

Resources