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

2

I'm having trouble making this communication, being that I'm responsible for the part of php and the part of the android is being made by a friend (that's the code sending something), he said he's sending by POST the most I can not find anything in the POST that it sends, because when I send it I give it a var_dump and I already enter the whole var_dump in the database to show it (it's serving to test), but 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;

  }

}
    
asked by anonymous 23.09.2016 / 23:21

1 answer

2

At first glance I suppose the code on the server is entering if (isset($_POST) ) , but it is reading the data sent by the client in the wrong way. In the Android code, all data sent is transformed into jsonobj.toString() string. So there is no way to have the 'key' key in the post $_POST['key']; array, it will not contain any data, since it was not sent in variable format1 & variavel2 & etc. You should get the contents of the request body (your json string) and then convert from json to array. More or less 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 in a simpler way, such as the restclient extension.

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

    
24.09.2016 / 17:53