【问题标题】:How do I know if I'm sending the file with outputstream我如何知道我是否正在使用输出流发送文件
【发布时间】:2018-04-04 16:35:11
【问题描述】:

我正在尝试使用 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

它们是什么意思?对吗?

非常感谢

【问题讨论】:

  • 请贴出相关代码(尽量简短,但要完整,便于理解)。
  • 我添加了代码谢谢
  • 我看到的第一件事是您正在通过 JSON 发送数据——因此您需要在 Connection 对象上设置属性 .setRequestProperty("Content-Type", "application/json; charset=UTF-8");。我也不熟悉.packData() 方法。你从哪个图书馆得到的?
  • 您好,我还包括了您推荐的参数,但没有任何改变!很抱歉,packdata () 是我用来创建 json 文件的更大类的一部分,但为了简化我将所有内容复制到同一个类中,否则我将不得不插入更多代码!事实上,即使我创建用于接收此数据的 php 文件也没有收到任何内容,因为如果我打印变量它不会打印任何内容!
  • 我必须承认,在设置 PHP 代码以接收 JSON 结构化数据时,我从来没有这么幸运过。所以我使用setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 并相应地构造我发送的数据。

标签: android send outputstream


【解决方案1】:

这是一个使用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());
        }
    }
}

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

【讨论】:

  • 这基本上会取代我在 asynctask 中的发送类吗?现在我试着让你知道!谢谢你 !!但是参数是我的json文件吗?
  • 是的,您从AsyncTask 或后台线程调用makeHttpRequestJsonString()。在我的示例代码中,该方法将返回一个包含 JSON 格式数据的字符串。您只需使用 JSONObject o = new JSONObject(json); 来获取您可以解析的 JSON 对象。
  • @Andrea :: 我编辑了我的答案以显示如何从AsyncTask 调用代码。如果您有任何问题,请告诉我。
  • 好的,谢谢!!你很善良!!现在我测试并告诉我它是如何工作的
猜你喜欢
  • 1970-01-01
  • 2011-07-19
  • 1970-01-01
  • 2017-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
相关资源
最近更新 更多