HTTP connection with server does not return JSON data

1

Hello, I'm trying to get the data from a query via HTTP, but it's returning this error:

org.json.JSONException: End of input at character 0 of

The code I have is this:

private class AsyncFetch extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(BuscaCAActivity.this);
    HttpURLConnection conn;
    URL url = null;
    String searchQuery;

    public AsyncFetch(String searchQuery){
        this.searchQuery=searchQuery;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tFazendo a busca...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL(minha_url);

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput to true as we send and recieve data
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // add parameter to our above url
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("codigo", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {
                return("Connection error");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }
    }

    @Override
    protected void onPostExecute(String result) {

        pdLoading.dismiss();
        if(result.equals("no result")) {
            Toast.makeText(BuscaCAActivity.this, getString(R.string.nenhum_resultado), Toast.LENGTH_LONG).show();
        }else{

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);

                    tvTeste.setText(json_data.getString("NRRegistro"));
                    tvTeste2.setText(json_data.getString("DataValidade"));
                    tvTeste3.setText(json_data.getString("Situacao"));
                    tvTeste4.setText(json_data.getString("NRProcesso"));
                }

            } catch (JSONException e) {

                e.printStackTrace();
            }

        }

    }

}

PHP looks like this:

if(isset($_POST['codigo']))
{
      require_once('config.inc.php');
      $search_query=$_POST['codigo'];

      $sql = 'SELECT NRRegistro, DataValidade, Situacao, NRProcesso  FROM tab_cadastro WHERE NRRegistro = :search_query';

      $statement = $connection->prepare($sql);
      $statement->bindParam(':search_query', $search_query, PDO::PARAM_STR);
      $statement->execute();
      if($statement->rowCount())
      {
            $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
            header('Content-type: application/json');
            echo json_encode($row_all);

      }  
      elseif(!$statement->rowCount())
      {
          echo "no result";
      }
}

I have been trying to find the error for some time and I have not been able to move forward. What is wrong with these codes?

    
asked by anonymous 01.10.2017 / 23:42

1 answer

1

It may be that the request is not returning value, or the result of your json is not passing in the onPostExecute () method

Try to separate responsibilities is good programming practice, it's easier to interpret code and fix errors.

  • Create a class that has the responsibility of requesting your url and bringing your json
  • HttpHandlerHelper

            public class HttpHandlerHelper {
    
        private static final String TAG = HttpHandlerHelper.class.getSimpleName();
        private static Context context;
        public HttpHandlerHelper(Context context) {
            this.context = context;
        }
    
        public String Request(String reqUrl) {
            String response = null;
            try {
                URL url = new URL(reqUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                // read the response
    
                if (200 <= conn.getResponseCode() && conn.getResponseCode() <= 299) {
                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    response = convertStreamToString(in);
                    return response;
                } else {
                    InputStream in = new BufferedInputStream(conn.getErrorStream());
                    response = convertStreamToString(in);
                    return response;
                }
    
            } catch (MalformedURLException e) {
                Log.e(TAG, "MalformedURLException: " + e.getMessage());
            } catch (ProtocolException e) {
                Log.e(TAG, "ProtocolException: " + e.getMessage());
            } catch (IOException e) {
                Log.e(TAG, "IOException: " + e.getMessage());
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
            return response;
        }
    }
    
    public static  String convertStreamToString(InputStream is) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append('\n');
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return sb.toString();
        }
    
  • Create the date template
  • Object Model

    public class ModelObjeto {
    
    public String registro;
    public String data_validade;
    public String situacao;
    public String processo;
    
    public ModelObjeto() {
    }
    
    public Atleta(String registro,
                  String data_validade,
                  String situacao,
                  String processo
    
    )
    {
        this.registro = registro;
        this.data_validade = data_validade;
        this.situacao = situacao;
        this.processo = processo;
    
    
    
    }
    
    public String getRegistro() {
        return registro;
    }
    
    public void setRegistro(String registro) {
        this.registro = registro;
    }
    
    public String getDataValidade() {
        return data_validade;
    }
    
    public void setDataValidade(String data_validade) {
        this.data_validade = data_validade;
    }
    
    public String getSituacao() {
        return situacao;
    }
    
    public void setSituacao(String situacao) {
        this.situacao = situacao;
    }
    
    public String getProcesso() {
        return processo;
    }
    
    public void setProcesso(String processo) {
        this.processo = processo;
    }
    

    }

  • Pass the part that mounts your json onto object to doInBackground ().

    public static class AsyncFetch extends AsyncTask<Void, Void, Void> {
    
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
    
            pdLoading.setMessage("\tFazendo a busca...");
            pdLoading.setCancelable(false);
            pdLoading.show();
    
        }
    
        @Override
        protected Void doInBackground(Void... arg0) {
    
            objetos = new ArrayList<>();
    
            HttpHandlerHelper handler = new HttpHandlerHelper();
            String json = handler.Request(minha_url);
    
            if(json != null && json.equals("no result")) {
    
                try {
    
                    JSONArray jArray = new JSONArray(json);
                    for (int i = 0; i < jArray.length(); i++) {
    
                        JSONObject json_data = jArray.getJSONObject(i);
                        ModelObjeto objeto = new ModelObjeto();
    
                        objeto.registro = json_data.getString("NRRegistro");
                        objeto.data_validade = json_data.getString("DataValidade");
                        objeto.situacao = json_data.getString("Situacao");
                        objeto.processo = json_data.getString("NRProcesso");
    
                        objetos.add(objeto);
                    }
    
                } catch (JSONException e) {
    
                    e.printStackTrace();
                }
    
            }
    
    
            return null;
        }
    
        @Override
        protected void onPostExecute(Void result) {
    
            pdLoading.dismiss();
    
        }
    
    }
    
  • 02.10.2017 / 04:24