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();
Related
I am trying to implement the MOT history API https://dvsa.github.io/mot-history-api-documentation/ and they give an example using CURL which works with the supplied api key successfully when using an online CURL tool.
I am trying to implement this in Android and realise I have to use something like HttpPost rather than CURL, this is my code:
//Tried with full URL and by adding the registration as a header.
//HttpPost httpPost = new HttpPost("https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests?registration=" + reg_selected);
HttpPost httpPost = new HttpPost("https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests");
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Accept", "application/json+v6");
httpPost.addHeader("x-api-key", "abcdefgh123456");
httpPost.addHeader("registration", reg_selected);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
InputStream inputStream = response.getEntity().getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String readLine = bufferedReader.readLine();
String jsonStr = readLine;
JSONObject myJsonObj = new JSONObject(jsonStr);
}else if (response.getStatusLine().getStatusCode() == 400){
//Bad Request Invalid data in the request. Check your URL and parameters
error_text = "Bad Request";
}else if (response.getStatusLine().getStatusCode() == 403){
//Unauthorised – The x-api-key is missing or invalid in the header
error_text = "Authentication error"; //<<<< FAILS HERE 403
}
response.getStatusLine().getStatusCode() returns • "403 – Unauthorised – The x-api-key is missing or invalid in the header".
However the x-api-key that I use works correctly with the online CURL test so the actual key is correct but how I am adding it to my android code request must be invalid or similar.
Can anyone throw any light as to the correct way to convert the CURL into Android java so that the server does not return 403?
Thanks
It's easy to do with Jsoup:
// CREATE CONNECTION
Connection conn=Jsoup.connect("URL_GOES_HERE");
// ADD POST/FORM DATA
conn.data("KEY", "VALUE");
// ADD HEADERS HERE
conn.header("KEY", "VALUE");
// SET METHOD AS POST
conn.method(Connection.Method.POST);
// ACCEPT RESPONDING CONTENT TYPE
conn.ignoreContentType(true);
try
{
// GET RESPONSE
String response = conn.execute().body();
// USE RESPONSE HERE
// CREATE JSON OBJECT OR ANYTHING...
} catch(HttpStatusException e)
{
int status = e.getStatusCode();
// HANDLE HTTP ERROR HERE
} catch (IOException e)
{
// HANDLE IO ERRORS HERE
}
Ps: I guess you are confused with Header and Post Data. The key etc (Credentials) must be used as Post Data and Content Type etc as Header.
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
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();
I'm working on creating an android app that will pull down user data from a MySQL database stored on a web server. I've read a few tutorials on HTTP Post that allows me to connect to the database, which I got working. However, I am unable to process the data that gets sent from the php.
The error I receive is: org.apache.http.MalformedChunkCodingException: Chunked stream ended unexpectedly.
This is the code I have written:
String name = username.getText().toString(); //username is a TextView field
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("user",name));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(location);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
Log.e("log_tag", "Error in http connection"+e.toString());
}
//Convert response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.i("log_tag", result);
}
catch(Exception e)
{
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
Log.e("log_tag", e.toString());
}
The error seems to appear in the convert response to string section. I've looked up several issues regarding similar errors to the one I received but what I read didn't seem to help much or I just don't know enough about http client coding...probably the latter. Any help would be greatly appreciated, thanks!
Here is the PHP as well:
<?php
$con = mysqli_connect("/**connection*/");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM userNames WHERE user='".$_POST['name']."')";
if ($result == NULL)
{
die();
}
else
{
//TODO:get row to java
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
print json_encode($rows);
mysql_close();
}
mysqli_close($con);
}
?>
The end goal of this is to convert the JSON response from the database into separate variables, the buffered reader stuff is just a middle step before the JSON conversion. Again , I just followed a tutorial so if anyone knows a different way of going about this I'm open to suggestions.
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.