安卓如何从php获取数据,如何从php服务器获取json数据到android mobile

小编典典

首先做URL连接

String parsedString = "";

try {

URL url = new URL(yourURL);

URLConnection conn = url.openConnection();

HttpURLConnection httpConn = (HttpURLConnection) conn;

httpConn.setAllowUserInteraction(false);

httpConn.setInstanceFollowRedirects(true);

httpConn.setRequestMethod("GET");

httpConn.connect();

InputStream is = httpConn.getInputStream();

parsedString = convertinputStreamToString(is);

} catch (Exception e) {

e.printStackTrace();

}

JSON字串

{

"result": "success",

"countryCodeList":

[

{"countryCode":"00","countryName":"World Wide"},

{"countryCode":"kr","countryName":"Korea"}

]

}

在下面,我正在获取国家/地区详细信息

JSONObject json = new JSONObject(jsonstring);

JSONArray nameArray = json.names();

JSONArray valArray = json.toJSONArray(nameArray);

JSONArray valArray1 = valArray.getJSONArray(1);

valArray1.toString().replace("[", "");

valArray1.toString().replace("]", "");

int len = valArray1.length();

for (int i = 0; i < valArray1.length(); i++) {

Country country = new Country();

JSONObject arr = valArray1.getJSONObject(i);

country.setCountryCode(arr.getString("countryCode"));

country.setCountryName(arr.getString("countryName"));

arrCountries.add(country);

}

public static String convertinputStreamToString(InputStream ists)

throws IOException {

if (ists != null) {

StringBuilder sb = new StringBuilder();

String line;

try {

BufferedReader r1 = new BufferedReader(new InputStreamReader(

ists, "UTF-8"));

while ((line = r1.readLine()) != null) {

sb.append(line).append("\n");

}

} finally {

ists.close();

}

return sb.toString();

} else {

return "";

}

}

2020-07-27

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值