Http request and Json parsing combination example (simple weather forecast system)

1. Effect display

write picture description here

2. First create an activity, modify the layout file inside, add controls, and set the id

<LinearLayout 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:orientation="vertical"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication2.WeatherTestActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="50dp">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="请输入城市名:"/>

        <EditText
            android:id="@+id/weather_test_et"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>
    <Button
        android:id="@+id/weather_test_btn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="查询"
        android:gravity="center"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="50dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:textSize="30sp"
            android:text="天气:"/>

        <TextView
            android:layout_marginLeft="10dp"
            android:id="@+id/weather_test_weather"
            android:layout_width="wrap_content"
            android:gravity="center"
            android:textSize="30sp"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="50dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:textSize="30sp"
            android:text="温度:"/>

        <TextView
            android:layout_marginLeft="10dp"
            android:id="@+id/weather_test_temp"
            android:layout_width="wrap_content"
            android:gravity="center"
            android:textSize="30sp"
            android:layout_height="wrap_content" />


    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="50dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:textSize="30sp"
            android:text="风力:"/>

        <TextView
            android:layout_marginLeft="10dp"
            android:id="@+id/weather_test_windpower"
            android:layout_width="wrap_content"
            android:gravity="center"
            android:textSize="30sp"
            android:layout_height="wrap_content" />


    </LinearLayout>

</LinearLayout>

3. Bind controls in the activity, set up monitoring, call custom classes, and start threads

public class WeatherTestActivity extends AppCompatActivity {

    private Button searchBtn;
    private EditText editText;
    private TextView weatherTv;
    private  TextView tempTv;
    private  TextView windTv;
    //在这里使用的是和风天气的api,登录和风天气的官网,获得普通用户挨批,添加key,地址则由输入的地址决定
    private String weatherAPI = "https://free-api.heweather.com/s6/weather/now?key=14134781d3024bf3945b32caeebf29ae&location=";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather_test);

        bangID();
        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //读取输入的地址,获得完整的天气预报api,传给子线程读取输入流
                String api_str = weatherAPI+editText.getText().toString();
                //在自定义类中添加构造方法,传值,启动线程时传入api
                new WeatherTest(WeatherTestActivity.this,editText,weatherTv,tempTv,windTv).execute(api_str);
            }
        });
    }

    private void bangID() {
        searchBtn = findViewById(R.id.weather_test_btn);
        editText = findViewById(R.id.weather_test_et);
        weatherTv = findViewById(R.id.weather_test_weather);
        tempTv = findViewById(R.id.weather_test_temp);
        windTv = findViewById(R.id.weather_test_windpower);
    }
}

4. Complete the parsing of Http request and Json data in the custom class (the obtained json data is placed in www.json.cn, so that the structure is clear and clear), so the project is completed, let's run it.

//在自定义类中完成Http请求和Json数据的解析
public class WeatherTest extends AsyncTask<String,Integer,String> {

    private EditText editText;
    private TextView weatherTv;
    private  TextView tempTv;
    private  TextView windTv;
    private Context context;
    //通过构造方法传值
    public WeatherTest (Context context,EditText editText,TextView weatherTv,TextView tempTv,TextView windTv){
        this.context = context;
        this.editText = editText;
        this.weatherTv = weatherTv;
        this.tempTv = tempTv;
        this.windTv = windTv;

    }





    @Override
    protected String doInBackground(String... strings) {
        InputStream inputStream = null;
        StringBuffer stringBuffer = null;

        try {
            //创建URL对象,接收api
            URL url = new URL(strings[0]);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            //判断是否联网
            if(httpURLConnection.getResponseCode()==200){
                inputStream = httpURLConnection.getInputStream();
            }
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            stringBuffer = new StringBuffer();
            String temp = null;
            while((temp=bufferedReader.readLine())!=null){
                stringBuffer.append(temp);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();

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


        return stringBuffer.toString();
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        try {
            //创建jsonobject对象,接收字符串
            JSONObject jsonObject  = new JSONObject(s);
            //创建jsonarray对象,接收数组
            JSONArray jsonArray = jsonObject.getJSONArray("HeWeather6");
            //创建jsonobject对象,接收数组的第一个对象
            JSONObject jsonObjectindex = jsonArray.getJSONObject(0);
            //创建jsonobject对象,接收对象
            JSONObject jsonObjectnow = jsonObjectindex.getJSONObject("now");
            //读取数据
            String cond_txt = jsonObjectnow.getString("cond_txt");
            String tmp = jsonObjectnow.getString("tmp");
            String wind_dir = jsonObjectnow.getString("wind_dir");
            String wind_sc  = jsonObjectnow.getString("wind_sc");
            //设置值
            weatherTv.setText(cond_txt);
            tempTv.setText(tmp+"℃");
            windTv.setText(wind_dir+wind_sc+"级");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325534134&siteId=291194637