Android中的网络编程
Posted lovelyYakir
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android中的网络编程相关的知识,希望对你有一定的参考价值。
谷歌在android6.0之后就废弃了使用HttpClinet进行网络连接。所以,这里需要重点学习的是通过HttpUrlConnect进行网络连接。
String path="这里是你想要的连接"; URL url=new URL(path); HttpURLConnection huc=(HttpURLConnection)url.openConnection(); huc.setConnectTimeout(3000); huc.setReadTimeout(3000);
//请求方式,Get或者Post; huc.setRequestMethod("Get"); //IO流操作 if(huc.getResponseCode()==200){ InputStream is=huc.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); StringBuffer sb=new StringBuffer(); String line; while((line=br.readLine())!=null){ sb.append(line); } sb.toString(); }
通常情况下,需要判断网络是否连接:
public Boolean isNet(Context context){ //通过上下文拿到系统的连接服务,返回一个ConnectivityManager对象 ConnectivityManager cm=(ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
//通过这个对象再拿到连接管理器。 NetworkInfo nwi= cm.getActiveNetworkInfo();
//判断是否有网 if(nwi!=null){ return nwi.isAvailable(); }else{ return false; } }
之后就是如果从网络解析数据:
Json解析:
谷歌官方的Gson解析数据:
首先写一个DataBean,用来获取Gson解析的数据,这里要特别注意解析的顺序,和对象名一定要和Json一样的格式:
{ "result": { "realtime": { "wind": { "windspeed": "0.0", "direct": "西南风", "power": "1级", "offset": null }, "time": "20:00:00", "weather": { "humidity": "35", "img": "1", "info": "多云", "temperature": "30" }, "dataUptime": "1467463816", "date": "2016-07-02", "city_code": "101270101", "city_name": "成都", "week": "6", "moon": "五月廿八" }, "life": { "date": "2016-7-2", "info": { "kongtiao": [ "部分时间开启", "天气热,到中午的时候您将会感到有点热,因此建议在午后较热时开启制冷空调。" ], "yundong": [ "较适宜", "天气较好,户外运动请注意防晒,推荐您在室内进行低强度运动。" ], "ziwaixian": [ "中等", "属中等强度紫外线辐射天气,外出时建议涂擦SPF高于15、PA+的防晒护肤品,戴帽子、太阳镜。" ], "ganmao": [ "少发", "各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。" ], "xiche": [ "不宜", "不宜洗车,未来24小时内有雨,如果在此期间洗车,雨水和路上的泥水可能会再次弄脏您的爱车。" ], "wuran": [ "较差", "气象条件较不利于空气污染物稀释、扩散和清除,请适当减少室外活动时间。" ], "chuanyi": [ "炎热", "天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。" ] } }, "weather": [ { "date": "2016-07-02", "week": "六", "nongli": "五月廿八", "info": { "dawn": null, "day": [ "1", "多云", "33", "南风", "微风", "06:05" ], "night": [ "7", "小雨", "22", "南风", "微风", "20:10" ] } }, { "date": "2016-07-03", "week": "日", "nongli": "五月廿九", "info": { "dawn": [ "7", "小雨", "22", "南风", "微风", "20:10" ], "day": [ "1", "多云", "31", "南风", "微风", "06:05" ], "night": [ "1", "多云", "22", "无持续风向", "微风", "20:10" ] } }, { "date": "2016-07-04", "week": "一", "nongli": "六月初一", "info": { "dawn": [ "1", "多云", "22", "无持续风向", "微风", "20:10" ], "day": [ "2", "阴", "31", "无持续风向", "微风", "06:05" ], "night": [ "3", "阵雨", "23", "北风", "微风", "20:10" ] } }, { "date": "2016-07-05", "week": "二", "nongli": "六月初二", "info": { "dawn": [ "3", "阵雨", "23", "北风", "微风", "20:10" ], "day": [ "1", "多云", "28", "南风", "微风", "06:06" ], "night": [ "7", "小雨", "23", "北风", "微风", "20:10" ] } }, { "date": "2016-07-06", "week": "三", "nongli": "六月初三", "info": { "dawn": [ "7", "小雨", "23", "北风", "微风", "20:10" ], "day": [ "8", "中雨", "29", "北风", "微风", "06:06" ], "night": [ "8", "中雨", "21", "北风", "微风", "20:10" ] } }, { "date": "2016-07-07", "week": "四", "nongli": "六月初四", "info": { "dawn": null, "day": [ "3", "阵雨", "27", "东北风", "微风", "07:30" ], "night": [ "3", "阵雨", "22", "东北风", "微风", "19:30" ] } }, { "date": "2016-07-08", "week": "五", "nongli": "六月初五", "info": { "dawn": null, "day": [ "3", "阵雨", "27", "东北风", "微风", "07:30" ], "night": [ "3", "阵雨", "22", "东北风", "微风", "19:30" ] } } ], "pm25": { "key": "", "show_desc": "0", "pm25": { "curPm": "54", "pm25": "34", "pm10": "54", "level": "2", "quality": "良", "des": "今天的空气质量是可以接受的,除少数异常敏感体质的人群外,大家可在户外正常活动。" }, "dateTime": "2016年07月02日20时", "cityName": "成都" }, "isForeign": 0 }, "error_code": 0, "reason": "Succes" }
DataBean:
package com.zhuoxin.bean; import java.io.Serializable; import java.util.List; public class WeatherDataBean implements Serializable{ /** * */ private static final long serialVersionUID = 1L; public String reason;//返回请求成功,或者是失败的原因 public Reslut result; public static class Reslut implements Serializable{ public Realtime realtime; public static class Realtime implements Serializable{ public String date;//当天的日期 public String time;//更新的时间 public String city_name;//当前的城市名称 public String week;//星期几 public String moon;//农历日期 public Wind wind; public static class Wind implements Serializable{ public String direct;//风向 public String power;//风力 } public Weather weather; public static class Weather implements Serializable{ public String info; //天气情况 public String temperature;//当前的温度 } } public Life life;//生活指数 public static class Life implements Serializable{ public Info info;//生活指数的info public static class Info implements Serializable{ List<String> kongtiao; List<String> yundong; List<String> ziwaixian; List<String> ganmao; List<String> xiche; List<String> wuran; List<String> chuanyi; } } List<FutureWeather> weather;//未来几天的天气数组的key public static class FutureWeather implements Serializable{ public String date;//未来几天天气的日期 public String week;//未来几天天气的星期几 public String nongli;//未来几天天气的农历日期 public Info info;//未来几天天气的info public static class Info implements Serializable{ List<String> day; //白天的天气信息 List<String> night;//晚上的天气信息 } } public Pm25 pm25; public static class Pm25 implements Serializable{ public Pm250 pm25; public static class Pm250 implements Serializable{ public String curPm;//当前pm2.5的值 public String quality;//空气情况 public String des; // 提示 } } } }
之后的事就非常简单了:
public <WeatherDataBean> parsejson(String json){ Gson gs=new Gson();
传两个参数:一个是Json连接,一个是DataBean的类。 return gs.fromJson(json, WeatherDataBean.class); }
XML解析这里讲谷歌的PULL解析XML,XML解析同样的要写一个DataBean用来存放解析出来要解析的数据:
XML:
<feed xmlns="http://www.w3.org/2005/Atom"> <title type="text">博客园_48小时阅读排行</title> <id>uuid:f59e7376-bd59-4244-91c8-c1d8a91207db;id=42519</id> <updated>2016-07-02T13:14:13Z</updated> <entry> <id>5631573</id> <title type="text">通过几个Hello World感受.NET Core全新的开发体验</title> <summary type="text"> 2016年6月27日,这是一个特殊的日子,微软全新的.NET开发平台.NET Core的RTM版本正式发布。我个人将.NET Core的核心特性归结为三点,它们的首字母组成一个非常好记的简称——COM,分别代表的含义Cross-Platform、Open-Source和Modularization。... </summary> <published>2016-06-30T23:19:00+08:00</published> <updated>2016-07-02T13:14:13Z</updated> <author> <name>Artech</name> <uri>http://www.cnblogs.com/artech/</uri> <avatar>http://pic.cnblogs.com/face/u19327.jpg</avatar> </author> <link rel="alternate" href="http://www.cnblogs.com/artech/p/net-core-hello-world.html"/> <diggs>59</diggs> <views>5023</views> <comments>58</comments> </entry> </feed>
Bean文件,同个生成get和set存取数据:
package com.yakir.databean; import android.graphics.Bitmap; /** * Created by qbqw7 on 2016/6/26. */ public class MainBolgData { private String id; private String title; private String summary; private String published; private String updated; private String name; private String uri; private Bitmap avatar; private String link; private String diggs; private String views; private String comments; private Bitmap topicIcon; private String sourceName; private String posts; private String comment; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getPublished() { return published; } public void setPublished(String published) { this.published = published; } public String getUpdated() { return updated; } public void setUpdated(String updated) { this.updated = updated; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public Bitmap getAvatar() { return avatar; } public void setAvatar(Bitmap avatar) { this.avatar = avatar; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getDiggs() { return diggs; } public void setDiggs(String diggs) { this.diggs = diggs; } public String getViews() { return views; } public void setViews(String views) { this.views = views; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } public Bitmap getTopicIcon() { return topicIcon; } public void setTopicIcon(Bitmap topicIcon) { this.topicIcon = topicIcon; } public String getSourceName() { return sourceName; } public void setSourceName(String sourceName) { this.sourceName = sourceName; } public String getPosts() { return posts; } public void setPosts(String posts) { this.posts = posts; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } }
PULL解析:
public List<Data> parseXml(InputStream is) { try {
// 建一个解析工厂 XmlPullParserFactory xpf=XmlPullParserFactory.newInstance();
//拿到解析器 XmlPullParser parser=xpf.newPullParser();
//给解析器装填原料 parser.setInput(is, "UTF-8"); //拿到解析的时间类型 int evenType=parser.getEventType();
//开始解析,做循环判断,如果不是xml文档末就一直解析 while (evenType!=XmlPullParser.END_DOCUMENT) { String tagaName=parser.getName(); switch (evenType) {
//开始解析xml的时候创建一个list容器存储对象,将data初始化。 case XmlPullParser.START_DOCUMENT: list=new ArrayList<Data>(); data=new Data(); break;
//解析标签,从标签头开始 case XmlPullParser.START_TAG:
//如果标签匹配了"entry"这个字符串就解析 if (tagaName.equals("entry")) { //如果标签匹配了"title"这个字符串就将这个标签后面的字符串取出来 }else if (tagaName.equals("title")) { data.setTitle(parser.nextText()); }else if (tagaName.equals("summary")) { data.setSummary(parser.nextText()); }else if (tagaName.equals("name")) { data.setName(parser.nextText()); }else if (tagaName.equals("updated")) { data.setUpdated(parser.nextText()); } if (tagaName.equals("comments")) {
//当判断到是末尾字符串标签的时候就把这个对象撞到list中 data.setComments(parser.nextText()); list.add(data); } break; case XmlPullParser.END_TAG: break; }
//如果数据多条,当取完了就应该跳到下一个事件类型。
eventType = parser.next();
最后来一波吉祥物:
//┏┓ ┏┓ //┏┛┻━━━┛┻┓ //┃ ┃ //┃ ━ ┃ //┃ ┳┛ ┗┳ ┃ //┃ ┃ //┃ ┻ ┃ //┃ ┃ //┗━┓ ┏━┛ // ┃ ┃ 神兽保佑 // ┃ ┃ 代码无BUG! // ┃ ┗━━━┓ // ┃ ┣┓ // ┃ ┏┛ // ┗┓┓┏━┳┓┏┛ // ┃┫┫ ┃┫┫ // ┗┻┛ ┗┻┛
以上是关于Android中的网络编程的主要内容,如果未能解决你的问题,请参考以下文章