zl程序教程

您现在的位置是:首页 >  前端

当前栏目

HTTP实现天气预报

HTTP 实现 天气预报
2023-09-14 09:04:30 时间

先在聚合数据网站上注册
XML文件:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">



    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/tx_show"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <EditText
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:id="@+id/edit_cityname"
        android:textSize="25sp"
        android:text="北京"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tx_show"
        />
    <Button
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:textSize="25sp"
        android:text="查询"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/edit_cityname"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

Java文件:

package com.example.httpdemo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    String CityName;
    TextView Tx_Show;
    WebView MyWB;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Tx_Show = findViewById(R.id.tx_show);
        final EditText ET_City = findViewById(R.id.edit_cityname);
        Button BTN_Find = findViewById(R.id.btn);

        BTN_Find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CityName = ET_City.getText().toString();//要在button监听里面获取编辑框里面的值

                Threap_Http threap_http = new Threap_Http();
                 threap_http.start();//一点击按键就开启非UI线程
            }
        });
    }

    private class Threap_Http extends Thread{//这里就是非UI线程了,点击button后,程序就开始执行这里的语句
        @Override
        public void run() {
            //组织可用来访问服务器的语句
            String WebURL = "http://apis.juhe.cn/simpleWeather/query";//网络地址,就是聚合数据那个网站里面的地址
            String API_Key = "60110cc0bb7993d48c4441f0b8059343";//聚合数据里面提供的key值
            String HttpURI = WebURL+"?"+"city="+CityName+"&"+"key="+API_Key;//这一串东西是用来访问服务器的
            try {
                //创建连接,用那语句进行访问
                CityName = URLEncoder.encode(CityName, "UTF-8");//将普通字符串转换成application/x-www-form-urlencoded MIME字符串
                URL httpUrl = new URL(HttpURI);//创建URL连接
                HttpURLConnection httpconn = (HttpURLConnection) httpUrl.openConnection();//再加上Http协议URL连接
                httpURLConnection.setConnectTimeout(3000);//连接超时
                httpURLConnection.setReadTimeout(5000);//连接后等待响应超时,程序里面可以捕获到超时异常,然后显示"系统正忙,请稍后再试"。这两句要同时设置

                //设置一个通道
                InputStream ins = httpconn.getInputStream();//创建一个字节流
                InputStreamReader inputStreamReader = new InputStreamReader(ins,"utf-8");//将字节流转换为字符流
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);//创建缓冲区,等缓冲区存满了再一次性发给磁盘,减少磁盘操作次数,速度提高很多
                String Str_json = bufferedReader.readLine();//最后读取数据并且赋值

                //格式转换,将json格式的文字转为Gson格式的
                Gson gson = new Gson();//创建Gson对象准备调用Gson类(tianqi.java)
                tianqi conToday = gson.fromJson(buffer,tianqi.class);//Gson框架调用fromJson方法,即从Json格式的buffer数据中获取信息,而且是在tianqi.class那个类里面,最后赋给tianqi类的对象
                String summary = conToday.getReason().toString();//对象的显示,getReason是类里面可调用的方法,即你想显示的什么内容

                //消息的设置
                Message msg = new Message();
                msg.what = 11;//用来给handle设置条件,是否发送
                Bundle data = new Bundle();//创建个对象放键和值的
                data.putString("k_json",Str_json);//k_json是键,Str_json是值,意思就是,将Str_json这个值放进键为k_json的data中
                msg.setData(data);//setdata对应下面的getdata
                handler.sendMessage(msg);//最后handle发送消息给UI进程

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }

    //中转站发消息的设置
    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 11:
                    Tx_Show.setText( msg.getData().getString("k_json").toString());//这边刷新文本框,有两个参数,getdata和getstring对应前面的setdata和putstring
                    break;


            }
        }
    };
}

网络权限:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

添加依赖:

implementation 'com.google.code.gson:gson:2.8.6'

右键MainActivity新建一个类,且将一段Json格式的文本粘进去生成
json文件:

{"reason":"查询成功!","result":{"city":"韶关","realtime":{"temperature":"7","humidity":"74","info":"阴","wid":"02","direct":"西北风","power":"3级","aqi":"21"},"future":[{"date":"2020-12-18","temperature":"5\/8℃","weather":"阴转多云","wid":{"day":"02","night":"01"},"direct":"北风转持续无风向"},{"date":"2020-12-19","temperature":"5\/9℃","weather":"多云","wid":{"day":"01","night":"01"},"direct":"北风转持续无风向"},{"date":"2020-12-20","temperature":"3\/12℃","weather":"多云","wid":{"day":"01","night":"01"},"direct":"持续无风向"},{"date":"2020-12-21","temperature":"4\/13℃","weather":"多云","wid":{"day":"01","night":"01"},"direct":"持续无风向"},{"date":"2020-12-22","temperature":"7\/15℃","weather":"多云","wid":{"day":"01","night":"01"},"direct":"持续无风向"}]},"error_code":0}

在这里插入图片描述
在这里插入图片描述
1