如何读取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:我/从服务器读取(526): 11-15 10:46:58.744:I /从服务器读取(526):(!)SCREAM:忽略错误抑制 11-15 10:46:58.744:I /从服务器读取(526):(!)注意:未定义的索引:在 4 上的C:\ wamp \ www \ younes_project \ younesservices.php中的json 11-15 10:46:58.744:I /从服务器读取(526):调用堆栈 11-15 10:46:58.744:I /从服务器读取(526):#TimeMemoryFunctionLocation 11-15 10:46:58.744:I /从服务器读取(526):10.0006142200 {main}().. \ younesservices.php : 0 11-15 10:46:58.744:I /从服务器读取(526): 11-15 10:46:58.744:我/从服务器读取(526): {“name”:“Hagrid”,“age”:“36”}
但我只读变量
这: {“name”:“Hagrid”,“age”:“36”}
答案 0 :(得分:0)
使用此代码。
public String getResult(String url){
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;
}