Send json object to local php server using HttpURLConnection - php

I am trying to send json object in android to local php server(XAMPP).
Here is my php script which recieves that object.
<?php
$response = array();
if (isset(($_POST['PNR_NO'])&&($_POST['Status'])&&($_POST['update_time']))){
$PNR_NO = $_POST['PNR_NO'];
$Status = $_POST['Status'];
$update_time = $_POST['update_time'];
// 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 pnr_database(PNR_NO, Status,update_time) VALUES('$PNR_NO', '$Status', '$update_time')");
// 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 {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}?>
And the java code that i am using is :
#Override
protected Void doInBackground(String... urls) {
OutputStream os;
HttpURLConnection conn = null;
try {
//constants
String pnr = "1234";
String stat = "WC12";
String updTime = "13:20";
Log.i("aaaaa", "Started");
URL url = new URL(urls[0]);
JSONObject jsonObject = new JSONObject();
jsonObject.put("PNR_NO",pnr );
jsonObject.put("Status", stat);
jsonObject.put("update_time", updTime);
String message = jsonObject.toString();
System.out.println(message);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /*milliseconds*/);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(message.getBytes().length);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
//open
conn.connect();
//setup send
os = new BufferedOutputStream(conn.getOutputStream());
os.write(message.getBytes());
Log.i("aaaaa","ended");
//clean up
os.flush();
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException ex) {
ex.printStackTrace();
}
finally {
//clean up
/*try {
os.close();
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
*/
conn.disconnect();
}
return null;
}
Basically I want to send data to my php server where I have created a database which has a table named pnr_database and the sent data should get stored in that table.I don't want any response from server.
But my code is not working...
I tested my php script from a html form where i was sending data to server... In that case php script was working fine and data was getting stored in database But i am not able to make it work in android.

This might be a little late answer. But the JSON you receive in php is encoded so you need to decode it as such in your if clause:
$decoded = json_decode($_POST, true); //this will return an array
$PNR_NO = $decoded['PNR_NO'];
$Status = $decoded['Status'];
$update_time = $decoded['update_time'];
Here you can enter the columns to your table.

Related

JSON_ERROR_SYNTAX sending Json request via Android App

I m trying to send a Json Post request using my Android Application.
But something weird happens.
Here is my Android Code:
try {
URL url = new URL(BASE_URL + params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.connect();
//JSonObject
JSONObject json = new JSONObject();
for(int i = 0 ; i < jsonValues.size(); i +=2){
json.put(jsonValues.get(i), jsonValues.get(i + 1));
}
jsonValues.clear();
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
//String encoded= URLEncoder.encode(json.toString(),"UTF-8");
output.writeBytes(URLEncoder.encode(json.toString(),"UTF-8"));
output.flush();
output.close();
int HttpResult = connection.getResponseCode();
if(HttpResult ==HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
String lineDecoded = URLDecoder.decode(line, "UTF-8");
sb.append(lineDecoded + "\n");
}
br.close();
System.out.println(""+sb.toString());
if(sb != null){
return sb.toString();
}else{
return null;
}
}else{
Log.d("ERRORRRRR",connection.getResponseMessage());
return connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} catch (JSONException e) {
e.printStackTrace();
return e.toString();
}
My php code is this:
$content = file_get_contents("php://input");
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0)
{
throw new Exception('Request method must be POST!');
}
//Make sure that the content type of the POST request has been set to
application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, true);
echo($decoded);
exit;
The $decoded is null when I make a request using my Android application and using json_last_error() function I get JSON_ERROR_SYNTAX.
This is the raw content of the post request:
{"name":"test","identifier":"12345677"}
But I can't understand what is the problem. In fact when I try to use Advance Rest Client to simulate the same request it works perfectly as shown in the picture below.
I finally solved my Problem.. It seems to be the
URLEncoder.encode(json.toString(),"UTF-8");
In fact removing it and sending just output.writeBytes(json.toString());
Everything works perfectly

sending values from android to php without namepair value

I want to send data from android to php.Am using android api 23 and from android's developers site a got to know that namepairvalue is deprecated from api 22 and above. I referred to one of the post here in stackoverflow and got the below code. but still it doesn't work.
My problem is that am sending a value(ID) to php code and based on that value fetching the records from database. Now if i fetch data without using this value it works fine, but i am unable to send the id value to php code.
i am unable to find whats wrong in this code or may be my fault is editing the code. It would be great if someone helps me to understand it clearly .
Thank you in advance.
Here is the code snippet that i have tried.
Android Code:
String sid = staffid.toString(); // this sid is passed as intent from another activity and passing it to below link.
Log.d("SID :", "" + sid);
try {
URL url = null;
url = new URL("http://usplhubli.96.lt/hrm/hrm_app/individual_view_staff.php");
Log.d("url to display :", "" + url.toString());
HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(CONNECTION_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
// Log.d("os to display :", "" + os.toString());
Uri.Builder builder = new Uri.Builder().appendQueryParameter("sid", sid);
Log.d("builder to display :", "" + builder.toString());
String query = builder.build().getEncodedQuery();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
Log.d("writer display :", "" + writer.toString());
writer.write(query);
writer.flush();
writer.close();
os.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (ProtocolException e2) {
e2.printStackTrace();
} catch (IOException e3) {
e3.printStackTrace();
}
return null;
}
I have this code in doInBackground(String... params) of AsyncTask
based on this sid value i have to get the data from database and display it in android activity.
Here is the PHP code that i have tried
PHP Code:
$response=array();
$sid=$_POST["sid"]; // this is the POST data that am send from android
//$sid="4"; // this is the static value that i have tried and its working
print_r($sid);
include 'dbconfig.php';
$imagePath='http://www.usplhubli.96.lt/hrm';
$query=mysqli_query($conn,"select * from hrm_staff where sid='$sid'");
if(mysqli_num_rows($query) >0) {
$response["hrm_staff"] = array();
while ($row = mysqli_fetch_array($query)) {
$recp = array();
$recp["sid"]=$row["sid"];
$fullName=$row['fname']."".$row['mname']."".$row['lname'];
$recp["name"]= $fullName;
$recp["address"]=$row['address'];
$recp['city']=$row['city'];
$recp["design"]=$row['did'];
$recp["contact"]=$row['mobile'];
$recp["email"]=$row['email'];
$recp['qualification']=$row['quali'];
$recp["dateofjoining"]=$row['doj'];
$ppic1=$row['ppic'];
$ppic1;
$ppic21=$imagePath."/".trim($ppic1);
$recp["ppic"]= $ppic21;
array_push($response["hrm_staff"], $recp);
}
$response["success"] = 1;
$response["message"]="display records";
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "No products found";
echo json_encode($response);
}
Please suggest. Thank you.
use these lines of code for using HttpURLConnection
For sending the request parameter are as:-
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("phone", number)
.appendQueryParameter("password", password)
.appendQueryParameter("device_login",value);
And for the getting the request parameter in the post method of connectionUrl are as follow:-
URL url = new URL(myurl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(30000);
urlConnection.setConnectTimeout(30000); ;
String query = builder.build().getEncodedQuery();
System.out.println("REQUEST PARAMETERS ARE===" + query);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
//Send request
DataOutputStream wr = new DataOutputStream (
urlConnection.getOutputStream ());
wr.writeBytes (query);
wr.flush ();
wr.close ();
//Get Response
InputStream isNew = urlConnection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(isNew));
String line;
response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
System.out.println("Final response===="+response);
There might be more than one issue but a big one is you never send the request, all you are doing is creating the request and setting up the parameters
you need to do a
conn.connect();
or
conn.getInputStream();
or any number of things you can do to send the request and get the information you require
AFTER you write your params

PHP inserts blank row into mysql table from android app

I am inserting json data from my android app in my device into xampp server in my computer using POST. It simply inserts row with empty column. When I enter the column from my browser using GET it converts it to numbers only eventhough the data is mix of numbers and letters. The type of the table column is varbinary. I entered 'crap' from my browser and it was inserted as '63726170' in the table. I am puzzled by this. Here is the PHP code that inserts the data.
if (isset($_POST)){
//sanitize the input
filter_var_array($_POST);
$ri=$_POST['regID'];
$id=json_decode($ri);
//$decoid= $id->regID;
if(is_array($id)){
foreach ($id as $key=>$value){
$fu=$id[$key];
};
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO regids (regID)
VALUES ('$fu')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}else{
echo "Error executing query!!!";
}
$conn = null;
I am adding my android code that is sending the data to the server
URL url;
HttpURLConnection urlConn;
DataOutputStream printout;
url = new URL ("myurlhere");
urlConn = (HttpURLConnection)url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.setRequestMethod("POST");
urlConn.connect();
/*List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("regID", result));*/
String result = args.toString();
try{
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("regID", result);
String postData="json="+jsonParam.toString();
// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeUTF(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
Log.i("NOTIFICATION", "Data Sent");
printout.flush ();
printout.close ();
OutputStreamWriter os = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
os.write(postData);
Log.i("NOTIFICATION", "Data Sent");
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String msg="";
String line = "";
while ((line = reader.readLine()) != null) {
msg += line; }
Log.i("msg=",""+msg);
os.close();

code works on emulator but not physical device

I have code that I'm trying to submit to a database, and the code works fine on an emulator but as soon as I move to an actual device the same code will no longer work. I think it has to do with the time() function in my php (I don't know what else it could be) but am I missing something obvious? this code on a physcial android device always throws "Oops! An error occurred." but on my emulator on my computer it works just fine. I've checked to make sure that I uploaded fresh copies of the project.
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['assemblyLotNumber']) && isset($_POST['assemblyID']) && isset($_POST['assemblerID']) && isset($_POST['quantity'])) {
$assemblyLotNumber = $_POST['assemblyLotNumber'];
$assemblyID = $_POST['assemblyID'];
$assemblerID = $_POST['assemblerID'];
$quantity = $_POST['quantity'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
$time = time();
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO assemblylot (assemblyLotNumber, assemblyID, assemblerID, date, isPremade, quantity) VALUES('$assemblyLotNumber', '$assemblyID', '$assemblerID', $time, 1, '$quantity')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "premade assembly successfully created.";
$response["date"] = $time;
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
$response["date"] = $time;
// 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);
}
?>
this is where I call it in the code
public void submitAssemblyLot(Assembly a) {
List<NameValuePair> assemblyParam = new ArrayList<NameValuePair>();
assemblyParam.add(new BasicNameValuePair("assemblyLotNumber", Integer.toString(a.getAssemblyLotNumber())));
assemblyParam.add(new BasicNameValuePair("assemblyID", Integer.toString(a.getAssemblyID())));
assemblyParam.add(new BasicNameValuePair("assemblerID", Integer.toString(a.getAssemblerID())));
try {
JSONObject json = jsonParser.makeHttpRequest(
url_submit_assembly_lot, "POST", assemblyParam);
String message = json.getString("message");
String date1 = json.getString("time");
Log.d("submitAssemblyLot", message);
Log.d("submitAssemblyLot", date1);
} catch (JSONException e) {
e.printStackTrace();
}
}

Getting BLOB from mysql database to android

I have a mysql database with the following schema
(int id, int sys_id, BLOB data)
There can be multiple data for the same sys_id, i.e. (1,1, blobdata1), (2,1, blobdata2) etc. are valid entries. the blob data is a compressed audio. When all the rows for a particular sys_id are combined a valid compressed audio data is produced.
I want to send this blob data to my android device. I have tried the following php code to send the data but it is not received as expected at the client side.
$conn = mysql_connect("localhost","root","");
mysql_select_db("mydb", $conn);
global $blobId;
$blobId = $_GET['id'];
$result = mysql_query("SELECT data FROM table WHERE sys_id=$blobId");
if( mysql_num_rows($result) == 0 )
die("No rows returned");
while($row = mysql_fetch_array($result) ) {
// is this correct way of concatenating binary data
$temp .= $row['data'];
}
// PROBLEM: what should be sent
echo $temp;
I don't mind if all the rows can be received at the client end and can be concatenated or operated upon locally there.
At the client side, I do the following:
// connect to the server
public void connect(URL url)
{
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
result = readStream(in);
//problem, how should I now parse the resultant string
decompress(result.getBytes()); // result.getBytes() returns null currently
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// for reading the incoming stream
public static String readStream(InputStream in) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(in),1000);
for (String line = r.readLine(); line != null; line =r.readLine()){
sb.append(line);
}
in.close();
return sb.toString();
}
// definition for decompression utility
public short[] decompress(byte[] codBytes);
you can encode the data you want to send in JSON format as
echo json_encode($response);
and send it as Json to your device and parse accordingly.
for parsing refer Here

Categories