HTTPConnection与JSON应用实例

本文介绍了一种使用JSON格式进行天气查询的方法。通过Android应用程序实现,包括创建URL、获取HTTPConnection对象、判断网络状态、创建输入流等步骤,并展示了具体的代码实现。

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

JSON:一种轻量级的数据交换格式。
JSONObject:一个json对象,包含一对儿(Key/Value)数值,在Key和Value之间是以逗号”,”分隔。
JSONStringer:json文本构建类,每个JSONStringer实体只能对应创建一个JSON text。
JSONArray:它代表一组有序的数值。将其转换为String输出(toString)所表现的形式是用方括号包裹,数值以逗号”,”分隔。
JSONTokener:json解析类 ;
JSONException:json中用到的异常 。

HTTPConnection
HTTP访问网络有两种方式:HttpClient和HttpURLConnection。

查询天气步骤:

  1. 创建URL,定义StringBuffer数组;
  2. 通过URL得到HTTPConnection对象;
  3. 判断网络是否疏通;
  4. 创建输入流InPutStream、BufferedReader
  5. 创建一个数组用来接收数据,判断是否接收的到数据;
  6. 在onPostExecute里面,先判断网络网络是否受到阻碍;
  7. 如果网络通畅,解析JSON数据包。

代码演示:

  <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="查询"/>
    <TextView
        android:id="@+id/wind_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="天气:"/>

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


</LinearLayout>

WeathActivity部分:

public class WeaActivity 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) {
              //在查询完一个城市后,可以继续输入查询另一个城市
              //API+cityET.getText().toString()是变的
                new MyTask().execute(API+cityET.getText().toString());
            }
        });
    }

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

        @Override
        protected String doInBackground(String... strings) {
            //1、找水源--创建URL
            URL url=null;
            StringBuffer stringBuffer=null;
            try{
                url=new URL(strings[0]);
                //2、开水闸--openConnection
                HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
                //3、建管道--InputStream
                InputStream inputStream=null;
                if(httpURLConnection.getResponseCode()==200){
                  //只有网络正常且返回数据正常时,才能创建输入流
                    inputStream= httpURLConnection.getInputStream();
                }else {
                    return "network_faild";
                }
                //4、建蓄水池蓄水--InputStreamReader
                InputStreamReader reader=new InputStreamReader(inputStream);
                //InputStreamReader reader=new InputStreamReader(inputStream,"UTF-8");

                //5、水桶盛水--BufferedReader
                BufferedReader bufferedReader=new BufferedReader(reader);

                stringBuffer=new StringBuffer();
               //tem是天气
                String temp="";

                //当tem传入的值不为空时,
                while ((temp=bufferedReader.readLine())!=null){
                    //stringBuffer可以读入tem的值
                    stringBuffer.append(temp);
                }
                bufferedReader.close();
                reader.close();
                inputStream.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //返回的是一堆未被解析的JSON数据
            return stringBuffer.toString();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if(s.equals("network_failed")){
                Toast.makeText(WeaActivity.this,"网络连接失败",Toast.LENGTH_SHORT).show();
            }
            else {

                //JSON 解析
                try {
                    JSONObject object = new JSONObject(s);
                    JSONObject obj = object.getJSONArray("HeWeather6").getJSONObject(0);
                    String temp = obj.getJSONObject("now").getString("tmp");
                    String wind = obj.getJSONObject("now").getString("wind_dir") + obj.getJSONObject("now").getString("wind_sc");
                    String weather = obj.getJSONObject("now").getString("cond_txt");
                    weatherTV.setText(weather);
                    windTV.setText(wind);
                    tempTV.setText(temp);
                } 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、付费专栏及课程。

余额充值