24-网络编程http和简单的JSON

来源:互联网 发布:visual studio mac版 编辑:程序博客网 时间:2024/05/29 10:43

学习java网络编程,首先要直到java.net 包, 包含了实现网络应用程序所需要的类。

  • URL 是表示统一资源定位符的类,它既是 URI 的旧式概念又是访问资源的方法。
  • URLConnection 是根据 URL 创建的,是用于访问 URL 所指向资源的通信链接。此抽象类将大多数工作委托给底层协议处理程序,如 http 或 ftp。
  • HttpURLConnection 是 URLConnection 的子类,提供一些特定于 HTTP 协议的附加功能。

    JSON解析 用到JsonOblect 和JsonArray

    从天气预报中获取相应城市的气象信息

    import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLConnection;public class HttpUtils {public static String doGetHttpUrlConnection() throws Exception{URL url = new URL("http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101110101&imei=e32c8a29d0e8633283737f5d9f381d47&device=HM2013023&miuiVersion=JHBCNBD16.0&modDevice=&source=miuiWeatherApp");URLConnection connection = url.openConnection();HttpURLConnection httpURLConnection = (HttpURLConnection) connection;httpURLConnection.setRequestMethod("GET");httpURLConnection.setRequestProperty("Charset", "utf-8");httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//IO流InputStream inputStream = null;InputStreamReader inputStreamReader = null;BufferedReader bufferedReader = null;StringBuffer stringBuffer = new StringBuffer();String tempLine = null;if (httpURLConnection.getResponseCode() >= 300) {//返回码throw new Exception("HTTP request is not success! " + httpURLConnection.getResponseCode());}try {inputStream = httpURLConnection.getInputStream();inputStreamReader = new InputStreamReader(inputStream, "utf-8");//字节流转字符流,utf-8编码方式bufferedReader = new BufferedReader(inputStreamReader);while((tempLine = bufferedReader.readLine()) != null){stringBuffer.append(tempLine);}} catch (Exception e) {// TODO: handle exception} finally{if (bufferedReader != null) {bufferedReader.close();}if (inputStreamReader != null) {inputStreamReader.close();}if (inputStream != null) {inputStream.close();}}return stringBuffer.toString();}}

    将抓取到的信息进行JSON解析


    将抓取到的数据,根据相应的格式进行解析,例如:

    {"name":"xiaoMing","city":[        {"name" : "郑州", "temperture":"25"},{"name" : "鹤壁", "temperture":"15"},{ "name":"周口", "temperture":"20"}      ],  "hero":{"name":"小炮"}}

    利用JSONObject 的实例化对象 jsonobject 存储上面的所有的信息

    String jsonString = "{\"name\":\"xiaoMing\",\"city\":[{\"name\":\"郑州\",\"temperture\":\"25\"},{\"name\":\"鹤壁\",\"temperture\":\"15\"},{\"name\":\"周口\",\"temperture\":\"20\"}],\"hero\":{\"name\":\"小炮\"}}";JSONObject jsonObject = JSONObject.fromObject(jsonString);jsonOblect.get("name");//可以获取到小明  这时jsonObject指向第一层的{}jsonObject.get("city");//得到city下的[]内的所有数据jsonObject = jsonObject.get("city");jsonObject.get(0);//得到{"name" : "郑州", "temperture":"25"}


     

    import net.sf.json.JSONArray;import net.sf.json.JSONObject;public class JSONTest {public static void main(String[] args) {String weather = null;try {weather = HttpUtils.doGetHttpUrlConnection();System.out.println(weather);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}JSONObject jsonObject = JSONObject.fromObject(weather);System.out.print("城市:");jsonObject = (JSONObject) jsonObject.get("forecast");System.out.println(jsonObject.get("city"));System.out.print("当前气温:");System.out.println(jsonObject.get("temp1"));System.out.print("当前风力:");System.out.println(jsonObject.get("fl1"));System.out.print("明天气温:");System.out.println(jsonObject.get("temp2"));System.out.print("穿衣指数:");System.out.println(jsonObject.get("index"));jsonObject = JSONObject.fromObject(weather);JSONArray jsonArray=  (JSONArray) jsonObject.get("index");System.out.println(jsonArray.get(0));}}


  • 1 0
    原创粉丝点击