时间:2021-07-01 10:21:17 帮助过:24人阅读
下面贴出实现代码,总算是可以从服务器上获取信息了
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教程有兴趣的朋友有所帮助。