javaphpandroidsendoutputstream

How do I know if I'm sending the file with outputstream


I'm trying to send a json file with OutputStream and BufferedWriter but if I print the logs this is the result !!

This is the simplification of the code from which I print the :

HttpURLConnection con;
       
    try {

            Log.v(TAG, "utilityBOopreation:Connect: entrato nel connect");

            URL url = new URL(urlAddress);
            con = (HttpURLConnection) url.openConnection();

            // set propertis
            con.setRequestMethod("POST");
            con.setConnectTimeout(1000);
            con.setReadTimeout(1000);
            con.setRequestProperty("Content-Type","application/json");
            con.setRequestProperty("Accept", "application/json");
            con.setDoInput(true);
            con.setDoOutput(true);
          //  Log.v(TAG, "utilityBOopreation:Connect: Valore della connessione :  " + con);

    con.connect();

    JSONObject jo= new JSONObject();
    

    try {
        jo.put("ID",Id);
        jo.put("GRM",GRM);
        / .
             altri campi
         ./

OutputStream os = con.getOutputStream();

        // Write
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
        bw.write(jo.tostring());

        Log.v(TAG,"Sender: Send : Il packData è stato inviato ");

        bw.flush();

        // RELEASE RES
       // Verifico i valori dolpo l' invio dei dati
        Log.v(TAG,"Sender: Send : Il risultato del HttpURLConnection " +
                        "Dopo l'invio dello streaming dati : " + con);
        Log.v(TAG,"Sender: Send : Il risultato del outputstreaming : " + os);

        bw.close();
        os.close();

            


        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.v(TAG, "utilityBOopreation:Connect: La connessione non è andata a buon fine : " + e);
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            Log.v(TAG, "utilityBOopreation:Connect: La connessione non è andata a buon fine : " + e);
            return null;
        } catch (JSONException | UnsupportedEncodingException e) {
        e.printStackTrace();
        Log.v(TAG,"DataPackager:packData:non sono riuscito a creare il json ... " + e.getMessage());
    }

This is the php code that receives the data:

<?php

// PER RESTITUIRE GLI ERRRORI A VIDEO
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL | E_STRICT);

// RICERCA DEI PRODOTTI
//
//

$host = 'localhost';
$username = 'user1';
$pwd = 'pass1';
$db = 'MIODB';


$json = file_get_contents("php://input");
$data = json_decode($json , true);
print ("JSON PASS FILE:");
print_r($json);
if(isset($_POST)){
$id = $data ['ID'];
print ("ID: ");
print_r($id);
print ("DATA :");
print_r($data);
$grm = $data ['GRM'];

  $response = array();
  
  $connect = mysqli_connect($host,$username,$pwd,$db) or die ('Unabletp connect');
  if(mysqli_connect_error($connect)){
      echo ("Fallita la connessione al data base".mysqli_connect_error());
  }

  $sql_find = ("SELECT prodoct FROM Mrkt_db
                WHERE  id ='$id' AND GRM ='$grm'");
  $result = mysqli_query($connect,$sql_find);
  if($result){
    $GENERAL= false;
    while ($row = mysql_fetch_array($result)){
      array_push($response,array("lane_prodoct"=>$row["lane_prodoct"],"pos_prodoct"=>$row["pos_prodoct"],"alt_prodoct" =>$row["alt_prodoct"],"r_l_prodoct"=>$row["r_l_prodoct"],"GENERAL" => GENERAL));
    }
    echo json_encode($response);
  }
  else{
    $sql_findGeneric = ("SELECT prodoct FROM GENERAL_MRKT 
                        WHERE  id ='$id' AND GRM ='$grm'") ;
    $result= mysqli_query($connect,$sql_findGeneric);
    if ($result) {
      $GENERAL= true;
      while ($row = mysql_fetch_array($result)){
        array_push($response,array("prodoct"=>$row["prodoct"]));
      }
      echo json_encode($response);
    }else {
      echo "no result";
    }
  }
  mysqli_close($connect);
}

When I try to print the values of outputstreaming and BufferedWriter the result is:

outputstreaming:

buffer(com.android.okhttp.internal.http.RetryableSink@f67f7d1).outputStream()

BufferedWriter:

java.io.BufferedWriter@96c6236

What do they mean? it's correct.


Solution

  • Here is a short example using setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    Just pass the url and the parameters to the method. The parameters are just key value pairs. The keys match the expected parameters in the php code.

    public String makeHttpRequestJsonString(String myUrlString, Map<String, String> params){
        String json = "";
        InputStream responseStream = null;
    
        String logMess = "";
        long startTime;
        long stopTime;
        long elapsedTime;
    
        try {
            startTime = System.currentTimeMillis();
    
            StringBuilder postData = new StringBuilder();
            for(Map.Entry<String, String> param : params.entrySet()){
                if(postData.length() != 0) postData.append('&');
                postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                postData.append('=');
                postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
            }
    
            byte[] postDataBytes = postData.toString().getBytes("UTF-8");
    
            URL url = new URL(myUrlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Cache-Control", "no-cache");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
    
            DataOutputStream request = new DataOutputStream(conn.getOutputStream());
            request.write(postDataBytes);
            request.flush();
            request.close();
    
            //Check the response code of the server -
            Integer replyCode = conn.getResponseCode();
            logMess += "   Reply Code:  " + replyCode.toString();
    
            responseStream = new BufferedInputStream(conn.getInputStream());
            BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
    
            stopTime = System.currentTimeMillis();
            elapsedTime = stopTime - startTime;
            logMess += "   elapsed Time :  " + elapsedTime + " ms";
    
            //Log.d(TAG, "makeHttpRequestJsonString --- " + logMess);
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
    
            while ((line = responseStreamReader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            responseStreamReader.close();
    
            json = stringBuilder.toString();
        }
        catch (UnsupportedEncodingException e) {
            Log.e(TAG, "makeHttpRequestJsonString --- " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "makeHttpRequestJsonString --- " + e.getMessage());
        }
        return json;
    
    }
    

    The PHP code that accepts and uses the parameters looks like this:

    <?php
    $response = array();
    $response["success"] = 0;
    $response["message"] = "Error at start";
    
    // check for post data
    if (isset($_POST['test_param1']) && 
        isset($_POST['test_param2']) && 
        isset($_POST['test_param3'])) {
    
        $test_param1 = $_POST['test_param1'];
        $test_param2 = $_POST['test_param2'];
        $test_param3 = $_POST['test_param3'];
    
        $response["success"] = 1;
        $response["message"] = "Parameters are correct";
    }
    else {
        $response["success"] = 0;
        $response["message"] = "Parameters are not correct";
    }
    // echoing JSON response
    echo json_encode($response);
    ?>
    

    Call the method from an AsyncTask or background thread. Example:

        private class GetWebDataTask extends AsyncTask<String, Integer, String>{
    
        @Override
        protected String doInBackground(String... params) {
            String result = "";
            try{
                String urlString = "http://example/yourScript.php";
    
                Map<String, String> params = new LinkedHashMap<String, String>();
                params.put("test_param1", "98kj73j8");
                params.put("test_param2", "98kj73j8");
                params.put("test_param3", "98kj73j8");
    
                res = makeHttpRequestJsonString(urlString, params);
    
                JSONObject jObj = new JSONObject(res);
                String success = jObj.getString("success");
                if(success.contentEquals("1")){
                    result = res;
                }// else maybe do something??
    
            }
            catch(Exception ex){
                Log.e(TAG, ex.getMessage());
            }
            return result;
        }
    
        protected void onPostExecute(String rawData) {
            try{
                if(!rawData.isEmpty()){
                    // Do something?
                }
            }
            catch(Exception ex){
                Log.e(TAG, ex.getMessage());
            }
        }
    }
    

    Please be aware that this is just an quick example and does not represent leanest or best practice coding. I also put the code together from a normal text editor, so there may me a few typos.