How to get SPECIFIC elements from a mysql database as Json - php

I am trying to get All the list of names and surnames from a mysql database but only for a certain username and password by which an user is accessing the service.
I tried with the code below but it seems that is not working. Actually the JSONArray i get back is EMPTY.
Here my java code and Php code (which is on the server).
The whole code is working great if I don't filter by username and password so actually i receive back the list. But as I try to filter by username and password the JsonArray is Null.
Please I will appreciate any clue!
public class ApiConnector {
public JSONArray GetAllCustomers(User user){
String url = "http://giacomoci.co.uk/FetchallDataList.php";
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("username", user.username));
dataToSend.add(new BasicNameValuePair("password", user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
DefaultHttpClient httpClient = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(url);
JSONArray jsonArray = null;
try {
//DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpGet httpGet = new HttpGet(url);
post.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse httpResponse = httpClient.execute(post);
HttpEntity httpEntity = httpResponse.getEntity();
if(httpEntity != null){
try {
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response : ", entityResponse);
jsonArray = new JSONArray(entityResponse);
}catch (JSONException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
} catch (ClientProtocolException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return jsonArray;
}
}
And here my PHP code
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT name, surname FROM Contacts WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
$user[] = array();
while($row = mysqli_fetch_assoc($statement)){
$user[] = $row;
}
echo json_encode($user);
mysqli_close($con);
So if I delete "Where username = ? AND password = ?" and the following line everything goes fine, but I get names and surnames for all the usernames and passwords, as I don't want. What's wrong with this code?

$username = $_POST["username"];
$password = $_POST["password"];
Replace those _POST with _GET
$username = $_GET["username"];
$password = $_GET["password"];

Related

MYSQL post not appearing

I dont think I have anything deprecated in my code, when I run the PHP script I get the success, but nothing appears in the database.
Heres the PHP Code.
<?php include "../inc/dbinfo.inc"; ?>
<?php
$connect = new mysqli("DB_SERVER","DB_USERNAME","DB_PASSWORD","DB_DATABASE");
if(!$connect){
die('error');
}
else
{
echo "success";
}
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$givenname = isset($_POST['givenname']) ? $_POST['givenname'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$phonenumber = isset($_POST['phonenumber']) ? $_POST['phonenumber'] : '';
$sql = "INSERT INTO test(username,password,givenname,email,phonenumber) VALUES ('$username', '$password', '$givenname', '$email', '$phonenumber')";
mysqli_close($connect);
?>
Heres the Android Code.
private void insertToDatabase(){
class SendPostReqAsyncTask extends AsyncTask<String, Void,String >
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
String paramGivenname = params[2];
String paramEmail = params[3];
String paramPhonenumber = params[4];
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", password.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("givenname", givenName.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("email", email.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("phonenumber", phone.getText().toString()));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Constantss.DB_DNS);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
// sendPostReqAsyncTask.execute(uname,pword, gname, lmail,pnumb);
}
I get the success from the Android Code to, but nothing appears in the database table.
Does anyone know the problem? Thanks!
You didn't execute the query.
So use:
mysqli_query($connect, $sql); and check for errors on it also.
References:
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli.error.php
Since another answer was given and I have pointed that out in comments first, just so we set the record straight.
You're also open to an sql injection. Use a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
You don't execute the query in your code. Also I would strongly suggest to sanitize the user input.
This asks for SQL injection. Consult: How can I prevent SQL injection in PHP?
Run the query:
$res = mysqli_query($connect, $sql);

Delete row from MySQL table via android

I need to delete an item from a list view on android when clicked. The thing is, my table is not on the phone(SQLite), but on the server. So I'm using a PHP code for this.
I have set up an onClickListener.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v,int position, long id) {
Show_Alert_box(v.getContext(),
"Please select action.", position);
}
});
public void Show_Alert_box(Context context, String message, int position) {
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(context)
.create();
//alertDialog.setTitle(getString(R.string.app_name_for_alert_Dialog));
alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
DBHandlerComments dbhelper = new DBHandlerComments(Comments.this);
SQLiteDatabase db = dbhelper.getWritableDatabase();
try{
JSONObject json2 = JSONParser.makeHttpRequest(urlDelete, "POST", params);
try {
int success = json2.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update product
}
} catch (JSONException e) {
e.printStackTrace();
}
//adapter.notifyDataSetChanged();
db.close();
}catch(Exception e){
}
}
});
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.setMessage(message);
alertDialog.show();
}
This is my JSONParser's makehttprequest code:
public static JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
//from here
while ((line = reader.readLine()) != null) {
if(!line.startsWith("<", 0)){
if(!line.startsWith("(", 0)){
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
`
And this is my PHP code:
$response = array();
if (isset($_POST['id'])) {
$id = $_POST['id'];
// include db connect class
$db = mysql_connect("localhost","tbl","password");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("shareity",$db);
// mysql update row with matched id
$result = mysql_query("DELETE FROM comments_activities WHERE id = $id");
// check if row deleted or not
if (mysql_affected_rows() > 0) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Product successfully deleted";
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
I'm adding the params like this:
params.add(new BasicNameValuePair(KEY_ID, id));
params.add(new BasicNameValuePair(KEY_AID, aid));
params.add(new BasicNameValuePair(KEY_ANAME, an));
params.add(new BasicNameValuePair(KEY_EVENT, ev));
params.add(new BasicNameValuePair(KEY_COMMENT, cb));
params.add(new BasicNameValuePair(KEY_USER, cby));
params.add(new BasicNameValuePair(KEY_TIME, cd));
I don't get any result. Can I know why?
I have noticed that you add unneeded parameters although you just need the id.
This is a simple code for deleting the given id, you can try it. If it worked, the error would be in your android code.
<?php
$servername = "your servername";
$username = "your username";
$password = "your password";
$dbname = "your dbname";
$link = mysql_connect($servername, $username, $password);
mysql_select_db($dbname, $link);
$id=$_POST['id'];
$result = mysql_query("DELETE FROM table_name WHERE id=$id", $link);
$response["success"] = 1;
$response["message"] = "Deleted successfully!";
echo json_encode($response);
?>
Change the servername to your database url and so on the other information.

Android Login Authentication failed

I have My databases on an xampp server and my activity and php file is given below. The problem in this page is that when I run application it always throws an exception. It always shows my last message that there is "Some problem is there." My submission date is due soon.
This is my Activity file
public class AdminLoginActivity extends Activity {
TextView username, password, message;
Button SignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_login);
StrictMode.enableDefaults();
username = (TextView) findViewById(R.id.adminusername);
password = (TextView) findViewById(R.id.adminpassword);
message = (TextView) findViewById(R.id.textView5);
SignIn = (Button) findViewById(R.id.adminloginbtn);
SignIn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
checkAdminData();
}
});
}
public void checkAdminData()
{
InputStream isr = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:1234/adminlogin.php");
try
{
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair> (2);
nameValuePairs.add(new BasicNameValuePair("username", username.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", password.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch (ClientProtocolException e)
{
Log.e("log_tag", "Error in Http connection " + e.toString());
message.setText("couldn't connect to database");
}
catch (IOException e)
{
}
String responseText = null;
try
{
String res = isr.toString();
// res = res.replaceAll("\\s+", "");
if (res.equals("1")) {
Intent i = new Intent(this, AdminMainPage.class);
startActivity(i);
}
else{
message.setText("Username or Password incorrect");
}
}
catch (Exception e)
{
Log.e("log_tag", "Sorry!! Incorrect Username or Password " + e.toString());
message.setText("Some problem is there");
}
}
}
PHP file:
<?php
$hostname_localhost ="localhost";
$database_localhost ="sibuilder";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select * from login l, admin a where a.username = '".$username."' AND l.password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo 0;
}
else {
echo 1;
}
?>
If you want to use your php script instead json format, can refer these questions
Android: AsyncTask to make an HTTP GET Request? Make an HTTP request with android to handle the response. Using AsyncTask is recommended.

Not getting all of data from Json object into database through PHP

I am trying to get all the Json data into my Mysql database through php, I have all my phone contacts details in this json object, But It only insert just one last phone contact detail to my database, please help as I have already posted a question but did not find a satisfactory answers. I debugged the application and it contains all of my contact detail in params of makehttprequest(.....)function, but Insert only last contact detail into database.
My php code is given below:
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['id']) && isset($_POST['phone'])&& isset($_POST['email'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO crm(id, name, phone, email) VALUES('$id', '$name', '$phone', '$email')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
My json object Which I copied during debugging the application is:
[id=85, name=, phone=, email=2, id=106, name=, phone=, email=2, id=93, name=, phone=, email=2, id=62, name=., phone=*100#, email=2, id=104, name=00, phone=00, email=2, id=90, name=03005103877, phone=03005103877, email=2, id=26, name=03005580234, phone=03005580234, email=2, id=154, name=Wajaht, phone=+923336124178, email=2, id=230, name=Yasir Altaf, phone=03215169284, email=2, id=55, name=Zafar Abbas, phone=03016775189, email=2]
But It it inserted the last contact detail which is name=Zafar Abbas, phone=03016775189, email=2 But I want insert all the detail in one go, please help me Thanks
AYsync task Class:
public class LoadSavingInDatabase extends AsyncTask<ArrayList<SavingContacts>,String,String>{
private static final String TAG_SUCCESS = "success";
private static final String URL = "http://amiranzur.com/android_connect/create_product.php";
JSONObject jsonObject= null;
#Override
protected String doInBackground(ArrayList<SavingContacts>... param) {
ArrayList<SavingContacts> contactArray = param[0];
List<NameValuePair> params = new ArrayList<NameValuePair>();
for(int i = 0; i < contactArray.size(); i++){
SavingContacts contact = contactArray.get(i);
params.add(new BasicNameValuePair("id", contact.id));
params.add(new BasicNameValuePair("name", contact.name));
params.add(new BasicNameValuePair("phone", contact.phone));
params.add(new BasicNameValuePair("email" , contact.email ));
}
JSONObject jsonObject= new JSONParser().makeHttpRequest(URL, "POST", params);
if(jsonObject != null){
try {
int success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("create","ok2");
bool = true;
Log.d("insert","true" + bool);
} else {
}
} catch (JSONException e) {
Log.d("exception","exc "+e);
Log.d("create","lpc");
}
}
else if(jsonObject == null){
Log.d("null", "null1");
bool = false;
}
return null;
}
}
protected void onPostExecute(boolean bool){
if(bool == false)
Log.d("Insertion failed", "ID already inserted");
}
Json P arser Class:
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
Log.d("Hope","Hope 1");
url += "?" + paramString;
Log.d("Hope","Hope 2");
HttpGet httpGet = new HttpGet(url);
Log.d("Hope","Hope 3");
HttpResponse httpResponse = httpClient.execute(httpGet);
Log.d("Hope","Hope 4");
HttpEntity httpEntity = httpResponse.getEntity();
Log.d("Hope","Hope 5");
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
Log.d("ex1","ex1 "+e);
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.d("ex1","ex2 "+e);
e.printStackTrace();
} catch (IOException e) {
Log.d("ex1","ex3 "+e);
e.printStackTrace();
}
try {
Log.d("Hope","Hope 6");
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
Log.d("Hope","Hope 7");
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.d("Hope","Hope 8");
is.close();
json = sb.toString();
Log.d("eee","json"+ json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + json);
}
//char[] chars = json.toCharArray();
// try parse the string to a JSON object
//if(chars[0] != 'D'){
try {
jObj = new JSONObject(json);
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
//}
//else {
// Log.d("null","null");
// }
return jObj;
}
}
The problem is here:
for(int i = 0; i < contactArray.size(); i++){
SavingContacts contact = contactArray.get(i);
params.add(new BasicNameValuePair("id", contact.id));
params.add(new BasicNameValuePair("name", contact.name));
params.add(new BasicNameValuePair("phone", contact.phone));
params.add(new BasicNameValuePair("email" , contact.email ));
}
JSONObject jsonObject= new JSONParser().makeHttpRequest(URL, "POST", params);
You make the request only after the loop,that will explain why you only INSERT the last value.
Move the request inside the loop so that you perform an insert at each iteration:
bool isSuccessful;
for(int i = 0; i < contactArray.size(); i++){
SavingContacts contact = contactArray.get(i);
params.add(new BasicNameValuePair("id", contact.id));
params.add(new BasicNameValuePair("name", contact.name));
params.add(new BasicNameValuePair("phone", contact.phone));
params.add(new BasicNameValuePair("email" , contact.email ));
//INSERT at each iteration
JSONObject jsonObject= new JSONParser().makeHttpRequest(URL, "POST", params);
if(jsonObject != null){
try {
int success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("debug", "Contact Id# " + contact.id +" Inserted");
} else {
Log.d("debug", "Contact Id# " + contact.id +" FAILED");
}
isSuccessful = true;
} catch (JSONException e) {
Log.d("exception","exc "+e);
Log.d("create","lpc");
isSuccessful = false;
}
}else{
Log.d("debug", "json is null");
isSuccessful = false;
}
}
return isSuccessful;

Sending and receiving json from android app to php script?

I am new to android development and I am trying to make a login page which sends the password and username to a php script as a json array and the php script returns a json array response which contains the meassage accordingly.
I have made a android code as:
jobj.put("uname", userName);
jobj.put("password", passWord);
JSONObject re = JSONParser.doPost(url, jobj);
Log.v("Received","Response received . . ."+re);
// Check your log cat for JSON reponse
Log.v("Response: ", re.toString());
int success = re.getInt("success");
if (success == 1) {
return 1;
}
else{
return 0;
}
}
catch(Exception e){ e.getMessage(); }
}
The JsonParser doPost code 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);
Log.v("entity",""+entity);
HttpResponse response;
try{
response = httpclient.execute(request);
Log.v("REceiving","Received . . .");
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
Log.v("RESPONSE",""+is);
}
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) {
Log.v("line",""+line);
sb.append(line + "\n");
}
Log.v("builder",""+sb);
is.close();
json = sb.toString();
} 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 (JSONException e) {
Log.v("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I have the php script as:
$response = array();
$con=mysqli_connect("localhost","uname","password","db_manage");
if((isset($_POST['uname']) && isset($_POST['password']))){
$empid = $_POST['uname'];
$pass = $_POST['password'];
$query = "SELECT mm_emp_id,mm_password FROM employee_master WHERE mm_emp_id='$empid'and mm_password='$pass'";
$result = mysqli_query($con, $query);
if(count($result) > 0){
$response["success"] = 1;
$response["message"] = "";
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "The username/password does not match";
echo json_encode($response);
}
}
I am getting undefined index at the line where I check for isset(). What am I doing wrong in receiving the json in php script?
If you can see I have used a link for my help
Please do help me out.
In the doPost method you don't use the JSON object (JSONobject c) that contains the variables
public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {
String url = "http://test.myhodo.in/index.php/test/execute";
#Override
protected JSONObject doInBackground(JSONObject... data) {
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
JSONObject jsonResponse = null;
HttpPost post = new HttpPost(url);
try {
StringEntity se = new StringEntity("json="+json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
jsonResponse=new JSONObject(resFromServer);
Log.i("Response from server", jsonResponse.getString("msg"));
} catch (Exception e) { e.printStackTrace();}
return jsonResponse;
}
Main Activity
try {
JSONObject toSend = new JSONObject();
toSend.put("msg", "hello");
JSONTransmitter transmitter = new JSONTransmitter();
transmitter.execute(new JSONObject[] {toSend});
} catch (JSONException e) {
e.printStackTrace();
}

Categories