当前位置:Gxlcms > PHP教程 > android客户端访问自己建立的服务器并返回JSON数据进行解析学习

android客户端访问自己建立的服务器并返回JSON数据进行解析学习

时间:2021-07-01 10:21:17 帮助过:24人阅读

最近在找关于客户端访问服务器开发的用例 总是去访问别人的网站也不能对里面的数据进行修改也不知道是怎么实现的,自己在网上申请了一个免费的服务器网站上传了一个php文件,现在就可以通过urlStr===http://1.hellowes.sinaapp.com/访问服务器上的信息了,并且服务器会返回一个数据,由于对php一点不懂所以服务器上返回的并不是真正的JSON数据,所以只好通过客户端字符串组合成一个JSON语句通过JSONObject进行解析出来,

下面贴出实现代码,总算是可以从服务器上获取信息了

public JSONObject getweb(String urlStr) throws Exception{

StringBuffer sb = new StringBuffer();
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setDoInput(true);
conn.setDoOutput(true);
if(conn.getResponseCode() == 200){
InputStream is = conn.getInputStream();
int len = 0;
byte[] buf = new byte[1024];
while((len = is.read(buf)) != -1){
sb.append(new String(buf, 0, len, "UTF-8"));
}
is.close();
}else{
throw new Exception("访问网络失败00");
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception("访问网络失败11");
}
System.out.println("---------"+sb.toString());
String htmlStr = sb.toString();
htmlStr = htmlStr.replaceAll("\"", "\'");
htmlStr = "{'singer':"+htmlStr+"}";
System.out.println("htmlStr===="+htmlStr);
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(htmlStr).getJSONObject("singer");
System.out.println("jsonObj===="+jsonObj);
} catch (JSONException e1) {
// TODO Auto-generated catch block

e1.printStackTrace();
}

return jsonObj;

}

以上就介绍了android 客户端访问自己建立的服务器并返回JSON数据进行解析学习,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

人气教程排行