如何在Android中将http响应放入数组中


How to put http response into array in Android

我正在尝试使用 Http 响应从 PHP 服务器获取数据,但这里棘手的是我以一个字符串的形式获取响应。我想将响应放入数组中。响应最初包含我从 MySQL 检索到的许多查询。我很感激任何帮助。

您应该使用数据交换格式(如 XMLJSON)在服务器端对响应进行编码。

然后,您可以在客户端轻松解析它。

Android对两者都有很好的支持,尽管JSON可能会更容易一些。

如果你的数据结构非常简单 - 例如单词列表 - 你可以使用CSV(逗号分隔值)和String.split()来获取数组:

String[] words = response.split(",");

JSON 示例(字符串数组)

[
   "The quick brown fox jumps over the lazy dog",
   "Jackdaws love my big sphinx of quartz",
   "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut"
]

JSONArray array = new JSONArray(response);
String[] sentences = new String[array.length()];
for (int i = 0, i < array.length(); i++){
    sentences[i] = array.getString(i);
}

试试这个...它将帮助您将响应存储在数组中。

           try
             {
                URL url = new URL("http:/xx.xxx.xxx.x/sample.php");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                 InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                 BufferedReader r = new BufferedReader(new InputStreamReader(in));
                 String x = "";
                 String total = "";
                 int i=0;
                 ArrayList<String> content = new ArrayList();
                 while((x = r.readLine()) != null)
                 {
                             content.add(x);
                 }
                 in.close();
                 r.close();
             }
             catch(Exception e)
             {
                 e.printStackTrace();
                 Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
             }

您可以将数组列表转换为数组。

              String ar[]= content.toArray(new String[content.size()]);

更好的方法是让你的 PHP Web 服务以 JSON 格式发送数据。 然后将其作为 接收,并解析 JSON 响应以获取所需的数据。我推荐 JSON,因为它比 xml 更轻,这将提高性能,减少带宽消耗。

尝试创建一个返回 JSON 数据的 php 脚本 这是检索数据并将它们放入数组的示例。

<?php
 $response = array();
 require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();  
$result = mysql_query("SELECT * FROM tbl_products") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$response["product"] = array();
while ($row = mysql_fetch_array($result)) {
    $product            = array();
    $product["products_id"]     = $row["table_id"];
    $product["products_price"]  = $row["transaction_no"];
$product['products_name']   = $row["table_total_price"];
    array_push($response["product"], $product);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No products found";
echo json_encode($response);
}
?>

这个是针对安卓的:

JSONObject json = jParser.getJSONFromUrl(NAME_OF_URL);
        Log.d("All Product List: ", json.toString());
        try {
            int success = json.getInt("success");
            if (success == 1) {
                products = json.getJSONArray("product");
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);
                    String id  =c.getString("products_id");
                    String price =c.getString("products_price");
                    String name = c.getString("products_name");
                }
            } else {
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }