访问中国天气网获取最近三天的数据

首先上一个效果图

这是本人在一款app中所用到的数据,获取最近三天中国天气网上的数据。

怎么说呢中国天气网上的数据比较乱,但是相比其他网站上的数据,中国天气网上的数据还是比较稳定的。

http://ws.webxml.com.cn/WebServices/WeatherWS.asmx 这个就是接口地址,上面不仅有天气的数据还有国家和城市的数据

可以采用webservice方式调用接口,也可以用java代码调用接口,我是采用java代码调用天气接口的

http://ws.webxml.com.cn/WebServices/WeatherWS.asmx?op=getWeather 天气预报接口地址


我是采用post方式调的接口

大家注意一下中国天气网上传过来的数据是一个一维数据,所以处理这个字符串就比较麻烦

这是我访问地址以及处理数据的代码

private void getWeather(String theCityName) {
        UIHelper.showDialogForLoading(getActivity(), "加载数据请稍后...", true);
        wts.clear();
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("theCityName", theCityName);

        RequestBody formBody = builder.build();
        final Request request = new Request.Builder().url(Contant.weatherurl)
                .post(formBody).build();
        client.newCall(request).enqueue(callback2);
    }

    // 请求后的回调方法
    private Callback callback2 = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            setResult2(e.getMessage(), false);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            setResult2(response.body().string(), true);
        }
    };

    // 显示请求返回的结果
    private void setResult2(final String msg, final boolean success) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (success) {
                    UIHelper.hideDialogForLoading();
                    System.out.println("msg::" + msg);
                    // InputStream input =new new
                    // ByteArrayInputStream(str.getBytes("UTF-8"))
                    try {
                        weather = (ArrayList<String>) XmlPull
                                .getWeather(new ByteArrayInputStream(msg
                                        .getBytes("UTF-8")));
                        // for(int i=0;i<weather.size();i++){
                        // System.out.println("i="+weather.get(i));
                        String weather1 = weather.get(6);
                        String weather2 = weather.get(5);
                        String weather3 = weather.get(7);
                        String weather4 = weather.get(8);
                        System.out.println("weather4="+weather4);
                        String[] weather11 = weather1.split(" ");
                        String[] weather44 = weather4.split("\\.");
                        //System.out.println("weather11="+weather11[0]+",weather11="+weather11[1]);
                        //System.out.println("weather44="+weather44[0]+",weather44="+weather44[1]);
                        Class<com.mtkj.scpublish.R.drawable> cls = R.drawable.class;
                        int value1 = cls.getDeclaredField("a_" + weather44[0])
                                .getInt(null);
                        WTEntity wt1 = new WTEntity(value1, weather11[0],weather11[1],
                                weather2 );
                        wts.add(wt1);
                        imgPic=(ImageView) view.findViewById(R.id.img_wt_m_pic);
                        txtSX=(TextView) view.findViewById(R.id.txt_sx);
                        txtCloud=(TextView) view.findViewById(R.id.txt_wt_cloud);
                        txtTemp=(TextView) view.findViewById(R.id.txt_wt_temp);
                        txtInfo=(TextView) view.findViewById(R.id.txt_wt_advic);
                        int value11 = cls.getDeclaredField("a_" + weather44[0]+"_d")
                                .getInt(null);
                        imgPic.setImageResource(value11);
                        txtSX.setText(mApp.post);
                        txtCloud.setText(weather2);
                        txtTemp.setText(weather1);
                        txtInfo.setText(weather.get(10));
                        
                        String weather5 = weather.get(12);
                        String weather6 = weather.get(13);
                        String weather7 = weather.get(14);
                        String weather8 = weather.get(15);
                        String[] weather66 = weather6.split(" ");
                        String[] weather88 = weather8.split("\\.");
                        int value2 = cls.getDeclaredField("a_" + weather88[0])
                                .getInt(null);
                        WTEntity wt2 = new WTEntity(value2, weather66[0],weather66[1],
                                weather5 );
                        wts.add(wt2);

                        String weather9 = weather.get(17);
                        String weather10 = weather.get(18);
                        String weather111 = weather.get(19);
                        String weather112 = weather.get(20);
                        String[] weather100 = weather10.split(" ");
                        String[] weather1122 = weather112.split("\\.");
                        int value3 = cls.getDeclaredField("a_" + weather1122[0])
                                .getInt(null);
                        WTEntity wt3 = new WTEntity(value3, weather100[0],weather100[1],
                                weather9 );
                        wts.add(wt3);
                        mApp.cachewts=wts;
                        mApp.wtpicId=value11;
                        mApp.wtSx=mApp.post;
                        mApp.wtcloud=weather2;
                        mApp.wttemp=weather1;
                        mApp.wtinfo=weather.get(10);

                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    UIHelper.hideDialogForLoading();
                    Toast.makeText(getActivity(), "数据加载失败,请稍后再试",
                            Toast.LENGTH_LONG).show();
                }

            }

            
        });
    }

还有一点大家要是想让自己app显示自定义图片,下载中国天气网上的图片包,将自己的图片名称改为对应天气图标即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
获取天气数据需要连接到中国天气的 API 接口。首先需要注册成为开发者,然后获取 API 接口的地址和 API key。然后在 Arduino 中使用 Ethernet 或 Wi-Fi 模块连接到互联,并使用 HTTP GET 请求来获取天气数据。你可以使用 Arduino 的 Ethernet 或 Wi-Fi 库,以及 JSON 解析库来处理响应数据。 以下是一个使用 Arduino 和 Ethernet 模块获取天气数据的简单示例代码: ```cpp #include <SPI.h> #include <Ethernet.h> #include <ArduinoJson.h> byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; IPAddress ip(192, 168, 1, 177); IPAddress server(218, 75, 157, 99); // 中国天气 API 地址 String apiKey = "your_api_key"; // 替换为你的 API Key EthernetClient client; char buffer[1024]; StaticJsonDocument<1024> jsonDoc; void setup() { Ethernet.begin(mac, ip); Serial.begin(9600); delay(1000); } void loop() { if (client.connect(server, 80)) { client.println("GET /api?city=上海&key=" + apiKey + " HTTP/1.1"); client.println("Host: www.weather.com.cn"); client.println("Connection: close"); client.println(); } while (client.connected() && !client.available()); int length = client.readBytesUntil('\n', buffer, sizeof(buffer)); buffer[length] = '\0'; if (strstr(buffer, "200 OK") != NULL) { while (client.connected() && client.available()) { length = client.readBytesUntil('\n', buffer, sizeof(buffer)); buffer[length] = '\0'; if (strstr(buffer, "Content-Length") != NULL) { int contentLength = atoi(strchr(buffer, ':') + 1); client.readBytes(buffer, contentLength); buffer[contentLength] = '\0'; DeserializationError err = deserializeJson(jsonDoc, buffer); if (err) { Serial.print("JSON deserialization failed: "); Serial.println(err.c_str()); } else { JsonObject weatherInfo = jsonDoc["weatherinfo"]; Serial.print("城市:"); Serial.println(weatherInfo["city"]); Serial.print("温度:"); Serial.println(weatherInfo["temp"]); Serial.print("风向:"); Serial.println(weatherInfo["WD"]); Serial.print("风力:"); Serial.println(weatherInfo["WS"]); Serial.print("湿度:"); Serial.println(weatherInfo["SD"]); Serial.print("发布时间:"); Serial.println(weatherInfo["time"]); } } } } else { Serial.println("HTTP request failed"); } client.stop(); delay(60000); // 每隔一分钟获取一次天气数据 } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值