0

如何在android中读取php文件发送的Json数据

这是php代码

$data = array("name" => "Hagrid", "age" => "36");                                                                    
$data_string = json_encode($data);  
echo $data_string;

这是读取数据android json的代码

InputStream instream = entity.getContent();

// String result = "";
Log.i("--------etat---------r","-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-");

String result = this.convertStreamToString(instream);
Log.i("--------etat---------r","-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-");

这里是分析InputStream对象的方法

public  String convertStreamToString(InputStream is) {

        convertStreamToString " );

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        StringBuilder sb = new StringBuilder();

        String line = null;
        try {

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");

            }
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();

            }
        }

        return sb.toString();

    }

但这是显示的代码

11-15 10:46:58.744:I/Read from server(526): 11-15 10:46:58.744: I/Read from server(526): (!) SCREAM:11-15 忽略错误抑制 10: 46:58.744:I/Read 从服务器(526):(!)注意:未定义的索引:C:\wamp\www\younes_project\younesservices.php 中的 json 在第4行 11-15 10:46:58.744:I/Read从服务器(526):调用堆栈 11-15 10:46:58.744:从服务器(526)I/读取:#TimeMemoryFunctionLocation 11-15 10:46:58.744:从服务器(526)I/读取:10.0006142200{main} ( )..\younesservices.php : 0 11-15 10:46:58.744: I/Read from server(526): 11-15 10:46:58.744: I/Read from server(526): {"name" :"海格","年龄":"36"}

但我只读变量

这:{“姓名”:“海格”,“年龄”:“36”}

4

1 回答 1

0

使用此代码。

公共字符串getResult(字符串网址){

    Log.v(TAG, "Final Requsting URL is : :"+url);

    String line = "";
    String responseData = null;

    try {
        StringBuilder sb = new StringBuilder();
        String x = "";
        URL httpurl = new URL(url);
        URLConnection  tc= httpurl.openConnection();


        /*URLConnection tc = twitter.openConnection();
        HttpURLConnection httpConnection = (HttpURLConnection) tc;
        httpConnection.setRequestMethod("POST");*/
        //tc.setRe
        //tc.setDoOutput(false);

        BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

        while ((line = in.readLine()) != null) {
            sb.append(line + "\n");
            x = sb.toString();
        }
        responseData = new String(x);
    }

   catch (FileNotFoundException e) {
       Log.v("NewWebHelper", "FileNotFoundException :");
        e.printStackTrace();
     }
    catch (IOException e) {
        Log.v("NewWebHelper", "IOException :");
        e.printStackTrace();
    }
  catch (Exception e) {
      Log.v("NewWebHelper", "Exception :");
        e.printStackTrace();
    }
    return responseData;
}
于 2013-04-13T11:14:33.240 回答