I'm trying to create an android application that connects to mySQL database through php and JSON.
THis is my php file on the server:
<?php
$host="my_host";
$username="my_name";
$password="my_password";
$db_name="my_db_name";
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT UserID, DisplayName
FROM User
WHERE (UserName LIKE '%it%') OR (DisplayName LIKE '%it%')";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['UserRes'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>
And this is my JSON java class code:
public class JSONClass extends AsyncTask<String,Void,String>{
public HashMap<String, String> tbl = new HashMap<String, String>();
private Context context;
public JSONClass(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... arg0) {
try{
String link = "some url";
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
I'm new with this and just want to get the basics and work from there. The php file should return one row as an answer, but as far as I can figure it out, the function falls in the try - catch part. I know that the result should come as HashMap. Can someone please tell me what I'm doing wrong or give me a tip to get the result? Thank you in advance!
This is how you fetch data from url, where url below is the web address of your PHP script:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
JSONArray ja = new JSONArray(result);
for(int i = 0 ; i < ja.length() ; i++){
String name = ja.getJSONObject(i).getString("name"); //write name of column
}
Related
I'm a novice creating a basic login app for Android, using 000webhost as my server.
My Java code:
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("name", user.name));
dataToSend.add(new BasicNameValuePair("email", user.email));
dataToSend.add(new BasicNameValuePair("password", user.password));
dataToSend.add(new BasicNameValuePair("leagueID", user.leagueID + ""));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost("http://subdomain.site88.net/register.php");
try{
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
}catch(Exception e){
e.printStackTrace();
}
return null;
My PHP code
<?php
$con = mysqli_connect("mysql1.000webhost.com", "username", "password", "dbname");
/***I want to get this data from Java side of application***/
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$leagueID = $_POST["LeagueID"];
/***this works
$name = "John Doe";
$email = "JohnDoe#gmail.com";
$password = "password"
$leagueID = 0;
***/
echo "Hello";//place this here to check website to see if its showing up
//Now we will add the name, email, password, and leagueID into a table called "user".
$statement = mysqli_prepare($con, "INSERT INTO user (email, name, password, leagueID) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "sssi", $email, $name, $password, $leagueID);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
//finish up by closing the connection
mysqli_close($con);
?>
If I hardwire the values into the PHP code instead of using the $_POST method, it is sent to the database as requested. However, it seems that the $_POST variable is empty. I'm not quite sure why this is the case. Is it perhaps that 000webhost has some sort of setting that doesn't allow for someone to post data?
Also, I'm aware that I'm using deprecated java methods and how insecure my password storage currently is. I'll modify that in the future, but I'd first like to know how to post data.
Thanks in advance!
HttpClient is now deprecated, so you should use HttpUrlConnection instead, to send post request to server.
Create a new Class which will send a asynchronous post request to your server.
public class YourAyncClass extends AsyncTask<String, Void, String>{
public YourAyncClass(Context c){
this.context = c;
}
public SaveCampaign(){}
protected void onPreExecute(){}
#Override
protected String doInBackground(String... arg0) {
try{
URL url = new URL("Your url here");
JSONObject urlParameters = new JSONObject();
urlParameters.put("name", "John Doe");
urlParameters.put("email", "john#doe.com");
urlParameters.put("password", "xxxxxx");
urlParameters.put("leagueId", "123-456");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(15000);
connection.setReadTimeout(15000);
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(urlParameters));
writer.flush();
writer.close();
os.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("New Exception : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
protected void onPostExecute(String result){
}
/*This method changes the json object into url encoded key-value pair*/
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
Now, to use this class in your method you need to implement following code in your code :
new YourAsyncClass(context).execute();
The above line of code calls the execute() method of AsyncTask class and starts the execution of your http call to server.
im am trying to get user data from my Date base hosted with wamp.
I sent a post request to an php file which return a json object but the app gets stuck in HttpResponse response = cliente.execute(request);
This is my code:
private void obtenerJson() {
EditText nombre = (EditText) findViewById(R.id.txtnombre);
EditText password = (EditText) findViewById(R.id.txtpassword);
String nombreIngresado = nombre.getText().toString().trim();
String passwordIngresado = password.getText().toString().trim();
List<NameValuePair> datos = new ArrayList<NameValuePair>();
datos.add(new BasicNameValuePair("nombre", nombreIngresado));
datos.add(new BasicNameValuePair("password", passwordIngresado));
HttpClient cliente = new DefaultHttpClient();
HttpPost request = new HttpPost("http://10.0.2.2/myfiles/myrequest.php");
BufferedReader lector =null;
StringBuffer stringBuffer = new StringBuffer("");
try {
request.setEntity(new UrlEncodedFormEntity(datos));
HttpResponse response = cliente.execute(request);
HttpEntity entidad = response.getEntity();
if (entidad != null) {
String resultado = EntityUtils.toString(entidad, "utf-8");
}
lector = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String linea = "";
String separadora = System.getProperty("line.separator");
while ((linea = lector.readLine()) != null){
stringBuffer.append(linea + separadora);
}
lector.close();
interpretarJSon(stringBuffer.toString(), nombreIngresado, passwordIngresado);
} catch (Exception e) {
}
}
The code below HttpResponse response = cliente.execute(request); doesn't matter.
The thing is that when I send the request, it return nothing. I use a Log.d to show the response content, but It has nothing to show.
This is my php code:
<?php include('funciones.php');
$nombre = $_POST["nombre"];
$password = $_POST["pass"];
$result = getSQLResultSet("SELECT nombre, password
FROM `usuario` where nombre=".$nombre."");
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
foreach ($row as $var => $comparar){
if($nombre == $var ){
$nombreok = true;
}
if($pass == $var){
$passok = true;
}
if($nombreok && $passok){
$devolver[] = $row;
}
}
}
echo json_encode($devolver);
?>
This is the code from funciones.php:
<?php
function getSQLResultSet($commando){
$mysqli = new mysqli("localhost", "root", "", "basededatos");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$var = $mysqli->execute($commando);
//return $mysqli->store_result();
$mysqli->close();
return $var;
}
?>
I think I might be using a wrong ip, or the problem is in my php code.
I will translate the code if necessary.
Thank you!
I am sending data from android to php script using json object as follows:
jobj.put("uname", userName);
jobj.put("password", passWord);
JSONObject re = JSONParser.doPost(url, jobj);
Then the doPost() method is as follows:
public static JSONObject doPost(String url, JSONObject c) throws ClientProtocolException, IOException
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
HttpEntity entity;
StringEntity s = new StringEntity(c.toString());
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
entity = s;
request.setEntity(entity);
HttpResponse response;
try{
Log.v("Request",""+request);
response = httpclient.execute(request);
//Log.v("response",""+response);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
}
catch(Exception e){
Log.v("Error in response",""+e.getMessage());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
//Log.v("Reader",""+reader.readLine());
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
//Log.v("response",sb.toString());
is.close();
json = sb.toString();
Log.v("response",json);
} catch (Exception e) {
Log.v("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (Exception e) {
Log.v("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
I have a php script which validates the input as follows:
$response = array();
$con=mysqli_connect("localhost","user","password","manage");
if((isset($_POST['uname']) && isset($_POST['password']))){
$empid = $_POST['uname'];
$pass = $_POST['password']);
$query = "SELECT empid,password FROM master WHERE mm_emp_id='".mysql_real_escape_string($empid)."' and mm_password='".mysql_real_escape_string($pass)."'";
$result = mysqli_query($con, $query);
if($result->num_rows != 0){
$response["success"] = 1;
$response["message"] = "";
print_r(json_encode($response));
}
else{
$response["success"] = 0;
$response["message"] = "The username/password does not match";
print_r(json_encode($response));
}
}
The problem is the isset() does not catch the uname key and I get undefined index for 'uname' and 'password' key. As you can see the json object is converted to string and added as String entity to the request. I cannot figure out what have I been doing wrong that the $_post is not receiving the values.
Please do suggest on what I have been doing so that i can receive the parameters in my php script.
you are posting data as application/json from android so you can access data in php with:
$post_data = json_decode(file_get_contents('php://input'));
Here my code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("dropbox link to php code");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
System.out.println(is);
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
System.out.println("1 " + result);
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
}
}
catch (JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
The link in the HTTPPost is a download link to the PHP code on Dropbox. That code looks like this:
<?php
mysql_connect("host","username","password");
mysql_select_db("1487057_test");
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
The problem is that the PHP code does not seem to be "executed" by the HTTPClient. When I do a print of the input stream, I just get back the first two lines of the PHP code. The JSON log does not seem to print at all. Anyone see what's wrong?
If you have the json data from ftp server it will work fine, since u r
using dropbox for php file, u need to make sure that it works, would
suggest you to test service on browser first if it works fine then u
can move ahead with code.possibly setup the ftp instead of Dropbox as
file server.
modify your PHP to something like:
<?php
$sql = "SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'";
mysql_query("set names utf8");
$result = mysql_query($sql);
while ($e = mysql_fetch_assoc($result)) {
$output[]=$e;
}
print(json_encode($output));
mysql_close($dbhost);
?>
I want to create a swing application and refer to the database using json.I tried but it did not work and i'm new to json.I want to access the database using webservice.
Below my code.
Login.java
String username=jTextField1.getText();
String password=jPasswordField1.getText();
JSONObject obj = new JSONObject();
obj.put("username", username);
obj.put("password", password);
try {
HttpClient httpclient= new DefaultHttpClient();
HttpResponse response;
HttpPost httppost= new HttpPost("http://localhost/kolitha/json_test/index.php");
StringEntity se=new StringEntity ("myjson: "+obj.toString());
httppost.setEntity(se);
System.out.print(se);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
response=httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("result is "+responseBody);
}
catch (Exception e) {
e.printStackTrace();
System.out.print("Cannot establish connection!");
}
index.php
here is my php file and i want to get the json object and parse username and password to query and send the response java application.
<?php
$json = file_get_contents('php://input',0,null,null);
$json_output = json_decode($json);
$username;
$password;
foreach($json_output -> details as $detail)
{
$username = $detail -> username;
$password = $detail -> password;
}
$login_result = false;
$connect = mysql_connect('localhost', 'root', '');
IF(!$connect)
{
die('Failed Connecting to Database: '.mysql_error());
}
$d = mysql_select_db("kolitha_json_test");
if (!$d)
{
echo "db not selected";
}
$sql = "SELECT * FROM login WHERE username='$username' AND password='$password' ";
$result = mysql_query($sql) or die (mysql_error());
if (!$result){
$login_result = false;
return $login_result;
die("Could not run the Query ".mysql_error());
} else {
$login_result = true;
return $login_result;
}
?>
try adding
request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
And check if the response has an entity
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String responseBody = RestClient.convertStreamToString(instream);
System.out.println("result is "+responseBody);
}