杂七杂八

网上的天气 API 哪一个更加可靠? http://www.zhihu.com/question/20575288

/**
*
*/

//System.out.println(jsonResult);
public static String request(String httpUrl) {
    BufferedReader reader = null;
    String result = null;
    StringBuffer sbf = new StringBuffer();
    try {
        URL url = new URL(httpUrl);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        InputStream is = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String strRead = null;
        while ((strRead = reader.readLine()) != null) {
            sbf.append(strRead);
            sbf.append("\r\n");
        }
        reader.close();
        result = sbf.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

public String request2(String string) throws HttpRPCException {
    URL url = null;
    String response = null;
    try {
        url = new URL(string);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw new HttpRPCException("网络连接错误", OAErrorConst.NETWORK_ERROR);
    }
    URLConnection conn = null;
    try {
        conn = url.openConnection();
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = is.read(buf)) > 0) {
            bos.write(buf, 0, len);
        }
        byte[] bytes = bos.toByteArray();
         response = new String(bytes);

    } catch (IOException e) {
        e.printStackTrace();
    }
    return response;
}

private void parseJSON() {
String httpUrl = “http://api.k780.com:88/?app=weather.today&weaid=101010100&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=xml“;
//String httpUrl = “https://api.heweather.com/x3/weather?cityid=CN101010100&key=7852d0c3ab7a42a88b24781de6add4af “;
String jsonResult = null;
try {
jsonResult = request2(httpUrl);

        //xml解析
        DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();

            DocumentBuilder builder=factory.newDocumentBuilder();//使用解析器工厂创建解析器
            Document document=builder.parse(jsonResult);//使用解析器解析文档生成树的document
           // 1.获得文档根元素对对象;
            Element root = document.getDocumentElement();




            // 获得文档根元素下一级子元素所有元素;
            NodeList nodeList = root.getChildNodes();
            Log.d("2",root.getNodeName());
         Log.d("2",nodeList.item(1).getNodeName());
           // System.out.println(root.getNodeName());

            NodeList list=document.getElementsByTagName("result");//得到文档中的所有Weather标签
           String a= list.item(7).getNodeValue();

           Log.d("4",a);
           // list.item(7).getChildNodes().item(2).getAttributes().item(0).getNodeValue();

            Node node =list.item(0);//得到第一个Weather
        Log.d("3",node.getNodeName());
        Log.d("3",node.getNodeValue());

// Node child=node.getFirstChild();//得到Weather标签的第一个子标签
// Node next=child.getNextSibling();//得到city的下一个标签

// while(next!=null){ //判断有没有走到最后一个标签
// if(next.getNodeType()==Node.ELEMENT_NODE){//判断节点类型是ELEMENT NODE
// Node content =next.getFirstChild(); //得到第一个子节点不能为空
// if(content!=null){
// System.out.println(next.getFirstChild().getNodeValue().trim());//String的trim方法去掉首位空格
// }
// }
// next=next.getNextSibling();
// }

    } catch (HttpRPCException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.d("1", "" + jsonResult);




}

public class GetWeatherInfoAgent extends AbstractAgent {
private long lastTime = -1;
private static WeatherInfo info;

@Override
protected WeatherInfo doExecute() throws HttpRPCException {
    if (System.currentTimeMillis() - lastTime > AppConst.INFO_TIMEOUT) {
        WeatherInfo newInfo = new WeatherInfo();
        info = newInfo;
        info = getJSONObject1();
        info = getJSONObject2(info);
        ////json准确数据
        String httpUrl = "http://api.k780.com:88/?app=weather.today&weaid=101010100&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
        String xml = getXML(httpUrl);
        Log.d("1", xml);
        ///XML数据
        String httpUrl2 = "http://api.k780.com:88/?app=weather.today&weaid=101010100&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=xml";
        String xml2 = getXML(httpUrl2);
        Log.d("1", xml2);


        lastTime = System.currentTimeMillis();
    }
    return info;
}

private WeatherInfo getJSONObject1() throws HttpRPCException {

    URL url = null;
    try {
        url = new URL("http://www.weather.com.cn/adat/sk/101010100.html");
    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw new HttpRPCException("网络连接错误", OAErrorConst.NETWORK_ERROR);
    }
    URLConnection conn = null;
    try {
        conn = url.openConnection();
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = is.read(buf)) > 0) {
            bos.write(buf, 0, len);
        }
        byte[] bytes = bos.toByteArray();
        String response = new String(bytes);

        JSONObject jsonObj = new JSONObject(response).getJSONObject("weatherinfo");

        String curtemp = jsonObj.getString("temp");
        String windPower = jsonObj.getString("WS");
        String moisture = jsonObj.getString("SD");
        info.setCurTemperature(curtemp);
        info.setWindPower(windPower);
        info.setMoisture(moisture);

    } catch (IOException e) {
        e.printStackTrace();
        throw new HttpRPCException("网络连接错误", OAErrorConst.NETWORK_ERROR);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return info;

}

private WeatherInfo getJSONObject2(WeatherInfo info) throws HttpRPCException {

    URL url = null;
    try {
        url = new URL("http://www.weather.com.cn/adat/cityinfo/101010100.html");
    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw new HttpRPCException("网络连接错误", OAErrorConst.NETWORK_ERROR);
    }
    URLConnection conn = null;
    try {
        conn = url.openConnection();
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = is.read(buf)) > 0) {
            bos.write(buf, 0, len);
        }
        byte[] bytes = bos.toByteArray();
        String response = new String(bytes);

        JSONObject jsonObj = new JSONObject(response).getJSONObject("weatherinfo");
        String weather = jsonObj.getString("weather");
        String mintemp = jsonObj.getString("temp2");
        String maxtemp = jsonObj.getString("temp1");
        info.setWeather(weather);
        info.setMaxTemperature(maxtemp);
        info.setMinTemperature(mintemp);

    } catch (IOException e) {
        e.printStackTrace();
        throw new HttpRPCException("网络连接错误", OAErrorConst.NETWORK_ERROR);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return info;
}


public String getXML(String string) throws HttpRPCException {
    URL url = null;
    String response = null;
    try {
        url = new URL(string);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw new HttpRPCException("网络连接错误", OAErrorConst.NETWORK_ERROR);
    }
    URLConnection conn = null;
    try {
        conn = url.openConnection();
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = is.read(buf)) > 0) {
            bos.write(buf, 0, len);
        }
        byte[] bytes = bos.toByteArray();
        response = new String(bytes);

    } catch (IOException e) {
        e.printStackTrace();
    }
    return response;
}


public WeatherInfo parseXML(String xml) throws ParserConfigurationException, IOException, SAXException {

// //先把string转成document对象
//
// //StringReader stringReader = new StringReader(xml);
//
// InputSource inputSource = new InputSource(xml);
// inputSource.setCharacterStream(new StringReader(xml));
// //xml解析
// DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = factory.newDocumentBuilder();//使用解析器工厂创建解析器
// Document document = builder.parse(inputSource);//使用解析器解析文档生成树的document
//
// Log.d(“2”,document.getInputEncoding());
// // 1.获得文档根元素对对象;
// Element root = document.getDocumentElement();
// Log.d(“2”, root.getTagName());
//
//
// NodeList nodes = document.getElementsByTagName(“success”);
// Log.d(“5”, nodes.item(1).getNodeValue());
//
//
// // 获得文档根元素下一级子元素所有元素;
// NodeList nodeList = root.getChildNodes();
// Log.d(“2”, nodeList.item(0).getNodeName());
// // Log.d(“2”, nodeList.item(1).getNodeName());
// // System.out.println(root.getNodeName());
//
// NodeList list = document.getElementsByTagName(“result”);//得到文档中的所有Weather标签
// String a = list.item(7).getNodeValue();
//
// Log.d(“4”, a);
// // list.item(7).getChildNodes().item(2).getAttributes().item(0).getNodeValue();
//
// Node node = list.item(0);//得到第一个Weather
// Log.d(“3”, node.getNodeName());
// Log.d(“3”, String.valueOf(node.getChildNodes()));
//

// Document document = DocumentHelper.parseText(xmlResult);//org.dom4j.DocumentHelper
// Element rootElement = document.getRootElement(); //得到根结点,即Response结点
// String res_bill_no = rootElement.elementTextTrim(“mailNo”);
// boolean res_success = Boolean.parseBoolean(rootElement.elementTextTrim(“success”));
return info;

}

}

你可能感兴趣的:(杂七杂八)