Trying to connect to local data base with Httppost - java

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!

Related

$_POST not receiving data from Java code

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.

Connecting android to mySQL using php and JSON

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
}

Parsing error! Can't parse Can't parse the stringorg.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

I'm currently working on android project related with database connectivity. As a part of App, there is an activity that form to insert data into database and retrieve the response whether it is inserted or not. Activity inserts data into database properly But, It fires an JSON parsing exception an couldn't get the response.
Here is my logcat scrreen:
03-31 09:49:38.196: D/JSON String:(884): Connection Error
03-31 09:49:38.236: D/Parsing Error!(884): Can't parse the stringorg.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
03-31 09:49:38.236: D/Exception!(884): java.lang.NullPointerException
03-31 09:49:38.526: W/InputMethodManagerService(373): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#b410d300 attribute=null, token = android.os.BinderProxy#b40b3160
Here is my PHP Database connection script:config.inc.php
I think it is faulty!!
<?php
$username = "homeyadmin";
$password = "8YvUPxCsVHEca2Ru";
$host = "localhost";
$dbname = "homey_db";
//Communicate via UTF8
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try {
//Is this required??
// $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
mysql_connect('localhost','$username','$password') or die("Connection Error");
mysql_select_db($dbname) or die("no db found");
} catch(PDOException $ex) {
die("Failed to connect to Database!" +$ex.toString());
}
/*header('Content-Type: text/html; charset=utf-8');
session_start();*/
?>
And finally JSONParser class:
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
try {
if (method == "POST") {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
Log.d("Input Stream:", is.toString());
} else if (method == "GET") {
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf8");
url += "?" +paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (Exception ex) {
ex.toString();
}
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();
json = sb.toString();
Log.d("JSON String:", json);
} catch (Exception e) {
Log.d("Buffer Error!", "Can't convert result" +e.toString());
}
//Time to parse the string into JSONObject
try {
jobj = new JSONObject(json);
} catch (JSONException ex) {
Log.d("Parsing Error!", "Can't parse the string" +ex.toString());
}
return jobj;
}
}
Here is my php code
<?php
require("config.inc.php");
if(!empty($_POST)){
if (empty($_POST['FNAME']) || empty($_POST['LNAME']) || empty($_POST['EMAIL']) || empty($_POST['PASS'])
|| empty($_POST['HNAME']) || empty($_POST['HPNO']) || empty($_POST['HADD2'])
|| empty($_POST['HLANDMARK']) || empty($_POST['HNAME'])
|| empty($_POST['HCOUNTRY']) || empty($_POST['HSTATE'])
|| empty($_POST['HCITY']) || empty($_POST['HPHONE'])) {
//Creating JSON response
$response["success"] = 0;
$response["message"] = "All the fields are required!";
die(json_encode($response));
}
//List OF variables
$fname = $_POST['FNAME'];
$lname = $_POST['LNAME'];
$email = $_POST['EMAIL'];
$pass = $_POST['PASS'];
$hname = $_POST["HNAME"];
$hpno = $_POST["HPNO"];
$hadd2 = $_POST["HADD2"];
$hland = $_POST["HLANDMARK"];
$hcon = $_POST["HCOUNTRY"];
$hstate = $_POST["HSTATE"];
$hcity = $_POST["HCITY"];
$hphone = $_POST["HPHONE"];
//If page not died
$result = mysql_query("SELECT 1 FROM owner_info WHERE owner_email = '$email'");
$num = mysql_num_rows($result);
echo $num;
$i = 0;
if($num = $i) {
//JSON Response
$response["success"] = 0;
$response["message"] = "Email ID is already in use!";
die(json_encode($response));
}
//If None of these condition followed
$query = "INSERT INTO
owner_info (owner_fname, owner_lname, owner_email, owner_pass)
VALUES('$fname', '$lname', '$email', '$pass')
";
if(mysql_query($query)){
echo "done";
}else{
echo mysql_error();
}
$result1 = mysql_query("SELECT owner_id
FROM owner_info
WHERE owner_email = '$email'
");
if ($result1) {
while ($row = mysql_fetch_assoc($result1)) {
echo $temp_owner_id = $row['owner_id'];
}
mysql_query("INSERT INTO
hostel_info (h_owner_id, h_name, h_plot_no, h_address2, h_landmark, h_country, h_state, h_city, h_contact_no)
VALUES ('$temp_owner_id', '$hname', '$hpno', '$hadd2', '$hland', '$hcon', '$hstate', '$hcity', '$hphone')
");
$response["success"] = 1;
$response["message"] = "Data inserted successfully.";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Database Error!!";
die(json_encode($response));
}
}
Please Help guys!!
You are getting invalid JSON, that's why it is not parsed.
Just add this code to see what you get from server:
try {
jobj = new JSONObject(json);
} catch (JSONException ex) {
Log.d("Parsing Error!", "Can't parse the string" +ex.toString());
Log.d("STRING_FROM_SERVER", json);
}

Cannot receive post parameters in php from android?

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'));

how to create a login with java and json web service

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);
}

Categories

Resources