Android: sending and receiving json with php and registering in the database

Asked

Viewed 809 times

2

I’m having trouble making this communication, being that I am responsible for the php part and the android part is being made by a friend(that the code sending something), he said he is sending by POST the information but is not getting anything in the POST he sends, because when there is the sending I give a var_dump and already insert the whole var_dump in the bank to then show (is serving to test) but still nothing is inserted.

Android:

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Locale;
import java.util.zip.GZIPInputStream;

/**
 * Created by daniel on 21/09/2016.
 */
public class JSONParser {

    public void sendData(String url) {
        JSONObject jsonobj; // declared locally so that it destroys after serving its purpose
        jsonobj = new JSONObject();
        try {
            // adding some keys
            jsonobj.put("key", "21/09/16-12:20-15654");

            // lets add some headers (nested headers)
            JSONObject header = new JSONObject();
            header.put("devicemodel", android.os.Build.MODEL); // Device model
            header.put("deviceVersion", android.os.Build.VERSION.RELEASE); // Device OS version
            header.put("language", Locale.getDefault().getISO3Language()); // Language
            jsonobj.put("header", header);
        } catch (JSONException ex) {
            ex.printStackTrace();
        }
        // Now lets begin with the server part
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httppostreq = new HttpPost(wurl);
            StringEntity se = new StringEntity(jsonobj.toString());
            //se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            se.setContentType("application/json;charset=UTF-8");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
            httppostreq.setEntity(se);
//          httppostreq.setHeader("Accept", "application/json");
//          httppostreq.setHeader("Content-type", "application/json");
//          httppostreq.setHeader("User-Agent", "android");
            HttpResponse httpresponse = httpclient.execute(httppostreq);
            HttpEntity resultentity = httpresponse.getEntity();
            if(resultentity != null) {
                InputStream inputstream = resultentity.getContent();
                Header contentencoding = httpresponse.getFirstHeader("Content-Encoding");
                if(contentencoding != null && contentencoding.getValue().equalsIgnoreCase("gzip")) {
                    inputstream = new GZIPInputStream(inputstream);
                }

                String resultstring = convertStreamToString(inputstream);
                inputstream.close();
                resultstring = resultstring.substring(1,resultstring.length()-1);
                //recvdref.setText(resultstring + "\n\n" + httppostreq.toString().getBytes());
//              JSONObject recvdjson = new JSONObject(resultstring);
//              recvdref.setText(recvdjson.toString(2));
            }
        } catch (Exception e) {
            //recvdref.setText("Error Occurred while processing JSON");
            //recvdref.setText(e.getMessage());
        }
    }

    private String convertStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        try {
            while ((line = rd.readLine()) != null) {
                total.append(line);
            }
        } catch (Exception e) {
        }
        return total.toString();
    }


    public static final String wurl = "http://192.168.3.140/app_com.php";
     }

PHP:

<?php
static $conn;
$conn = mysqli_connect('localhost', 'root', 'root', 'ProjetoPesquisa');
$cont = var_dump($_POST);

if (isset($_POST) ) {

  $info = $_POST['key'];

  if(isset($info)){

    $query = "INSERT INTO Monitoramento(paciente, info) VALUES(12345678105, '$info')";


    $linha = mysqli_query($conn, $query);

    return true;

  }else{

   // $query = "INSERT INTO Monitoramento(paciente, info) VALUES(12345678105, '$info')";
    $query = "INSERT INTO Monitoramento(paciente, info) VALUES(12345678105, '$cont')";
    //$query = "DELETE FROM Monitoramento where info='';";

    $linha = mysqli_query($conn, $query);
    var_dump($linha) . "</br>";

    $linha = mysqli_query($conn, "select * FROM Monitoramento");

    while($t = mysqli_fetch_array($linha)){
      echo "</br>" .$t['info'] ."</br>";
    }

    return false;

  }

}

1 answer

2


At first glance I suppose the code on the server is entering the if (isset($_POST) ) , but it is reading the data sent by the client in the wrong way. In the Android code all the data sent are transformed into string jsonobj.toString(). So there can be no key in the post array $_POST['key'];, it will not contain any data, as it was not sent in variable1&variavel2&etc. You must take the content of the request body (its json string) and then convert it from json to array. Sort of like this:

$info = file_get_contents('php://input');
$arrayinfo = json_decode(info);

You can use some browser plugin that allows you to test your api more simply, such as the restclient extension.

There is a question in stackoverflow with more details on how to receive json on server

Browser other questions tagged

You are not signed in. Login or sign up in order to post.