Android学习--HttpUrlConnection+JSON应用实例

本文介绍了一个基于Android平台的简易天气应用程序开发过程。该应用通过网络请求获取指定城市的实时天气信息,并展示风力、温度等数据。文章详细展示了如何设置网络权限、使用AsyncTask进行后台数据加载、解析JSON数据及UI绑定等关键技术点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实例天气预报

步骤:

  1. 添加网络权限

     <uses-permission android:name="android.permission.INTERNET" />
  2. 设置布局视图,activity文件中绑定ID,设置按钮的点击事件,将API网址传值过来,设置输入框输入城市

  3. 创建MyTask类继承AsyncTask,设置三个参数
  4. 在doInbackground方法中,(找水源)创建URL,请求返回,(开水闸)设置openConnection,(建管道)InputStream,
  5. 判断网页返回码是否为200正确,如果网络正常且返回数据正常,我们才能创建,否则返回“network_failed”
  6. (建蓄水池蓄水)InputStreamReader,(水桶盛水)BufferReader
  7. 设置temp,判断当读取temp是否能读取,当他不为空的时候,提取值,否则直接退出
  8. 返回stringBuffer.toString(),返回到JSON数据
  9. 在onPostExcute方法中,判断如果网络返回码错误,提示网络连接失败,否则就正常返回,做JSON解析判断,区分是{}还是【】来定义是object还是array,获得各种风力温度
  10. 赋值

    视图代码展示

 <EditText
        android:id="@+id/city_et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/search_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查询"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="天气:"/>
        <TextView
            android:id="@+id/wind_tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="温度:"/>
        <TextView
            android:id="@+id/temp_tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="风力:"/>
        <TextView
            android:id="@+id/weather_tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>

activity代码演示:

public class Weather2Activity extends AppCompatActivity {
    private EditText cityET;
    private TextView weatherTV;
    private TextView windTV;
    private TextView tempTV;
    private Button searchBtn;
    private String API="https://free-api.heweather.com/s6/weather/now?key=73faf20c8cdc4935943a9703a9068b4f&location=";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wea);

        bindID();

        searchBtn.setOnClickListener(  new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MyTask().execute(API+cityET.getText().toString());
            }
        });
    }

    class MyTask extends AsyncTask<String,String,String>{

        @Override
        protected String doInBackground(String... strings) {
            StringBuffer stringBuffer=new StringBuffer();
            try {
                URL url=new URL(strings[0]);//请求返回
                HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                InputStream inputStream=null;
                if (connection.getResponseCode()==200) {
                    inputStream=connection.getInputStream();//还有网络正常且返回数据正常,我们才能创建
                }else {
                    return "network_failed";
                }

                InputStreamReader reader=new InputStreamReader(inputStream);
                BufferedReader bufferedReader=new BufferedReader(reader);

                String temp=null;
                while ((temp=bufferedReader.readLine())!=null){
                    stringBuffer.append(temp);
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return stringBuffer.toString();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(s.equals("network_failed")){
                Toast.makeText(Weather2Activity.this,"连接失败",Toast.LENGTH_SHORT).show();
            }else {
                //JSON解析
                try {
                    JSONObject object=new JSONObject(s);
                    JSONArray array=object.getJSONArray("HeWeather6");
                    JSONObject object1=array.getJSONObject(0);
                    JSONObject newobject=object1.getJSONObject("now");
                    String wind=newobject.getString("cond_txt");
                    String weather=newobject.getString("wind_dir")+newobject.getString("wind_sc")+"级";
                    String tmp=newobject.getString("tmp");

                    //赋值
                    weatherTV.setText(weather);
                    windTV.setText( wind);
                    tempTV.setText(tmp);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void bindID() {
        cityET=findViewById(R.id.city_et);
        windTV=findViewById(R.id.wind_tv);
        tempTV=findViewById(R.id.temp_tv);
        weatherTV=findViewById(R.id.weather_tv);
        searchBtn=findViewById(R.id.search_btn);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值