我怎么知道我是否正在使用 outputstream 发送文件

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

我正在尝试发送带有 OutputStream 和 BufferedWriter 的 json 文件,但如果我打印日志,结果就是这样!!

这是我用来打印 :

的代码的简化版

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());
    }

这是接收数据的php代码:

<?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);
}
?>

当我尝试打印 outputstreaming 和 BufferedWriter 的值时,结果是:

输出流:

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

缓冲写入器:

java.io.BufferedWriter@96c6236

它们是什么意思?正确吗?

非常感谢

这是一个使用 setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

的简短示例

只需将 url 和参数传递给该方法。参数只是键值对。这些键与 php 代码中的预期参数匹配。

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;

}

接受和使用参数的PHP代码如下所示:

<?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);
?>

AsyncTask 或后台线程调用方法。示例:

    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());
        }
    }
}

请注意,这只是一个简单示例,并不代表最精益或最佳实践编码。我也是用普通的文本编辑器把代码放在一起的,所以可能会有一些错别字。