I am trying sending data from Android application to web server. My android application is working successfully.However php code have problems.
<?php
$json = $_SERVER['HTTP_JSON'];
echo "JSON: \n";
var_dump($json);
echo "\n\n";
$data = json_decode($json,true);
echo "Array: \n";
var_dump($data);
echo "\n\n";
$name = $data['name'];
$pos = $data['position'];
echo "Result: \n";
echo "Name : ".$name."\n Position : ".$pos;
?>
Errors:
Notice: Undefined index: HTTP_JSON in C:\wamp\www\jsonTest.php on line 2
( line 2 : $json = $_SERVER['HTTP_JSON']; )
I couldn't find these problems reason. Can you help me ?
( note: I am using wamp server )
Here is the relevant Android source:
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("10.0.2.2:90/jsonTest.php";);
JSONObject json = new JSONObject();
try {
json.put("name", "flower");
json.put("position", "student");
JSONArray postjson=new JSONArray();
postjson.put(json);
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
if(response != null)
{
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
text = sb.toString();
}
tv.setText(text);
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
This code works successfully on android side(no error). But php side has problems..
Thanks.
This isn't where your JSON is:
$json = $_SERVER['HTTP_JSON'];
You possibly meant:
$json = $_POST['HTTP_JSON'];
Where HTTP_JSON is the POST variable name you gave to your JSON in your Android app.
The rest of the errors stem from the fact that json_decode is failing because you're not successfully reading the JSON data from the request. You can check the response of json_decode to check if it was successful as follows:
$data = json_decode($json,true);
if( $data === NULL)
{
exit( 'Could not decode JSON');
}
Finally, passing true as the second parameter to json_encode means it will return an associative array, so you'd access elements like so:
$name = $data['name'];
$pos = $data['position'];
Make sure you read the docs for json_encode so you understand what it's doing.
Edit: Your problem is that you're accessing the $_POST parameter by the wrong name. You should be using:
$json = $_POST['jsonpost'];
Since the following line names the parameter "jsonpost":
httppost.getParams().setParameter("jsonpost",postjson);
Since I don't know how the java client sends the request
I would try :
print_r($_SERVER);
print_r($_GET);
print_r($_POST);
To figure out how it does.
try these lines:
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
Related
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
Good Day Internet!
I am trying to retrieve and display an image from mysql database into an image view (android). The image is a blob type. I have the following php code that gets the image from mysql.
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
require 'connect_aircraftoperator.php';
$image = $db->query("SELECT * FROM company");
while ($row = $image->fetch_assoc()) {
echo '<img src="data:image/png;base64,' . base64_encode($row['companyImage']) . '" />';
}
?>
Below is my android code for now with the use of JSON.
try {
//setting up the default http client
HttpClient httpClient = new DefaultHttpClient();
//specify the url and the name of the php file that we are going to use
//as a parameter to the HttpPost method
HttpPost httpPost = new HttpPost("http://10.0.2.2//aircraftoperatorapp/leimage.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//getting the response
HttpResponse response = httpClient.execute(httpPost);
//setting up the entity
HttpEntity httpEntity = response.getEntity();
//setting up the content inside an input stream reader
//lets define the input stream reader
is = httpEntity.getContent();
}
catch (Exception e) {
System.out.println("Exception 1 Caught ");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
//create a string builder object to hold data
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line+"\n");
}
//use the toString() method to get the data in the result
fullNameResult = sb.toString();
is.close();
//checks the data by printing the result in the logcat
System.out.println("---Here's my data---");
System.out.println(fullNameResult);
}
catch (Exception e){
System.out.println("Exception 2 Caught ");
}
//result now contains the data in the form of json
//let's inflate it in the form of the list
try {
//creates json array
JSONArray jArray = new JSONArray(fullNameResult);
for (int i = 0; i < jArray.length(); i++)
{
//create a json object to extract the data
JSONObject json_data = jArray.getJSONObject(i);
imageTemp = json_data.getString("companyImage"); //gets the value from the php
}
//this line should display the image from the mysql database into an image view
}
catch (Exception e){
//System.out.println("Exception 3 Caught ");
Log.e("lag_tag", "Error Parsing Data " + e.toString());
}
Thanks in advance for any help!
First use Base64 decode the string to byte array:
byte[] data = Base64.decode(imageTemp);
Bitmap b = BitmapFactory.decodeByteArray(data,0,data.length,null);
I am going to implement the client-to-Server module which request is sent from Android devices to php . When it comes to the implementation , I have no clue why the server side cannot receive the json sent from Android device . As for the server, the database insert module is OK but cannot catch the json values . Would you please tell me what is wrong with the client side ?
The below is my code
Client side Android
public String postData(String argument , String url) {
String result="";
// Create a new HttpClient and Post Header
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 60000 * 20;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 60000 * 20;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
HttpConnectionParams.setSocketBufferSize(httpParameters, 8*1024);
DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
//Log.d("url" , url);
HttpPost httppost = new HttpPost(url);
try {
System.out.println("Response:"+ "start execute");
JSONObject json = new JSONObject();
json.put("userid","loka");
json.put("password","yoor");
json.put("email","johnsmith#example.com");
//Log.d("test" , jsonString);
httppost.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
httppost.setHeader( "Content-Type", "application/json" );
//httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
//If php json response required
if(status==200){
HttpEntity getResponseEntity = response.getEntity();
InputStream httpResponseStream = getResponseEntity.getContent();
result = slurp(httpResponseStream , 8192);
System.out.println("result: "+ result);
}else{
System.out.println("2");
result = String.valueOf(status);
HttpEntity getResponseEntity = response.getEntity();
InputStream httpResponseStream = getResponseEntity.getContent();
result = slurp(httpResponseStream , 8192);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return e.getMessage();
} catch (ConnectTimeoutException e){
e.printStackTrace();
return e.getMessage();
}catch (IOException e) {
e.printStackTrace();
return e.getMessage();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
Server side php
<?php
header('Content-type: application/json');
ini_set('display_errors','On');
require_once 'lib_mysql/insert.php';
$json = file_get_contents('php://input');
$result =insertUser($json);
if($result) {
echo "success";
}
else{
echo "fail";
}
?>
include_once("connection.php");
function insertUser($jsonString){
$usern = $jsonString->userid; //Undefined Variables
$pass = $jsonString->password; //Undefined Variables
$email = $jsonString->email; //Undefined Variables
$conn = getDBConn();
$data = false;
You need to use json_decode() function in php. header('Content-type: application/json'); would not help in this case
Try this way hope this helps you
Relpace
httppost.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
with
httppost.setEntity(new StringEntity(json.toString(), HTTP.UTF_8));
I have been searching everywhere this question and the only answer i've seen is JSON! I feel there is also other ways to do this.
My problem is i can post data from android to php script to insert data to my server. But what i want to do is get some data from my php to android. (without using JSON).
Please, i'm still in the basics. Make this as simple as possible!
Here's my php script:
<?php
$con=mysqli_connect("HOST", "USER", "PASSWORD", "DB_NAME");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$tablenamep = $_POST["tablenamep"];
$stringp = $_POST["stringp"];
$val = mysqli_query($con, "DESCRIBE `$tablenamep`");
if($val == TRUE) {
echo "Table exists";
$stringp = "This ID already exists. Try again!";
} else {
echo "Table does not exist";
mysqli_query($con, "CREATE TABLE ".$tablenamep." ( name VARCHAR(30), number INT, email VARCHAR(30))");
$stringp = "Your ID is available";
}
mysqli_close($con);
?>
This is how i used my java class to post data to php script.
public void CONNECT_SERVER(){
String msg = etID.getText().toString();
if (msg.length()>0){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myfile.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("tablenamep", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
} else {
Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show(); }
}
The php script and android app is working FINE, no errors! Now i can add the data from my android app to the php script. NO PROBLEMS TILL NOW!
BUT WHAT I WANT, is to get the $stringp variable from the php script above to my android app after executing the script. In other words i want my app to know whether the ID exists or not.
I have already checked many forums regarding this question. SOLVE THIS PROBLEM WITHOUT JSON.
You must use json or other parsing method to retrieve data from server
try this
contact.php
<?php
mysql_connect ("localhost","root","");
mysql_select_db("meetapp");
$output=array();
$q=mysql_query("SELECT `app_id` FROM `registration`");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print (json_encode($output));
mysql_close();
?>
in your java code
try {
HttpClient httpclient2 = new DefaultHttpClient();
HttpPost httppost2 = new HttpPost("http://10.0.2.2:80/contact.php");
HttpResponse response2 = httpclient2.execute(httppost2);
HttpEntity entity2 = response2.getEntity();
is2 = entity2.getContent();
Log.e("log_tag", "connection success ");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
try
{
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb2 = new StringBuilder();
String line = null;
while ((line = reader2.readLine()) != null)
{
sb2.append(line + "\n");
}
is.close();
result3=sb2.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
try
{
JSONArray jArray2 = new JSONArray(result3);
String s11;
Log.w("Lengh",""+jArray2.length());
for(int i=0;i<jArray2.length();i++){
JSONObject json_data2 = jArray2.getJSONObject(i);
s11=json_data2.getString("app_id");
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
Here is my code to send the data from android app to php app which is running in my localhost. It is showing "Connection to http:// localhost refused" . Please help me
public void postData() throws JSONException
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/xampp/FeelSafeSecurity/connectiondemo.php");
JSONObject json = new JSONObject();
try {
// prepare JSON data:
json.put("name", "santhosh");
json.put("age", "24");
JSONArray postjson=new JSONArray();
postjson.put(json);
// Post the data:
httppost.setHeader("json", json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
// Execute HTTP Post Request
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
// for JSON:
if(response != null)
{
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
text = sb.toString();
}
tv.setText(text);
}
catch (ClientProtocolException e)
{
System.out.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And here is my php code to receive the data. I'am new to PHP.
<?php
$json = $_SERVER['HTTP_JSON'];
echo "JSON: \n";
echo "--------------\n";
var_dump($json);
echo "\n\n";
$data = json_decode($json);
echo "Array: \n";
echo "--------------\n";
var_dump($data);
echo "\n\n";
echo "Result: \n";
echo "--------------\n";
echo "\n\nName : ".$data->name."\n\n Age : ".$data->age;
?>
Don't use localhost use your IP address. Localhost is only for the LOCAL server
localhost means the local machine on which the app executes. In your case either amdroid device or the emulator virtual machine. Neither of which is running your php server.
So, if you run this on device you must use the IP of the machine where php code is running.
If you are trying this on emulator and you host machine runs the php code then you might try 10.0.2.2 as described in emulator network addressing.