Http请求和Json解析结合实例—-天气预报项目
首先创建一个WeatherActivity,修改布局文件,添加控件,设置id
xml文件 activity_weather
<?xml version="1.0" encoding="utf-8"?>
<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:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.urlapplication.WeatherActivity">
<EditText
android:id="@+id/city_et"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="请输入城市名"/>
<Button
android:id="@+id/search_btn"
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="查询"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/weather_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="天气:"
android:textSize="30sp"/>
<TextView
android:id="@+id/temp_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="温度:"
android:textSize="30sp"/>
<TextView
android:id="@+id/wind_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="风力:"
android:textSize="30sp"/>
</LinearLayout>
</LinearLayout>
接着 在WeatherActivity内绑定id,设置监听,启动线程,并使用Http请求和Json解析结合
package com.example.administrator.urlapplication;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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 WeatherActivity extends AppCompatActivity {
private TextView weatherTV;
private TextView windTV;
private TextView tempTV;
private TextView searchBtn;
private TextView cityET;
//网络获取,和风天气
private String weatherAPI="https://free-api.heweather.com/s6/weather-now?key=f4df0dc926f54557b9c94b6c09451b51&location=";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
bindID();
searchBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String city=cityET.getText().toString();
new MyTask().execute(weatherAPI+city);
}
});
}
class MyTask extends AsyncTask<String,String,String>{
@Override
protected String doInBackground(String... strings) {
StringBuffer stringBuffer=new StringBuffer();
try {
//创建URL对象,接收api
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="";
while ((temp=bufferedReader.readLine())!=null){
stringBuffer.append(temp);
}
bufferedReader.close();
reader.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);
if (s.equals("network_failed")){
Toast.makeText(WeatherActivity.this,"网络连接失败",Toast.LENGTH_SHORT).show();
}else {
//JSON解析
try {
//创建jsonobject对象,接收字符串
JSONObject object=new JSONObject(s);
//创建jsonarray对象,接收数组
JSONArray array=object.getJSONArray("HeWeather6");
//创建jsonobject对象,接收数组第一个对象
JSONObject object1=array.getJSONObject(0);
//创建jsonobject对象,接收对象
JSONObject nowObj=object1.getJSONObject("now");
//读取数据
String weather=nowObj.getString("cond_txt");
String wind=nowObj.getString("wind_dir")+nowObj.getString("wind_sc")+"级";
String temperature=nowObj.getString("tmp");
weatherTV.setText(weather);
windTV.setText(wind);
tempTV.setText(temperature);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
private void bindID(){
cityET=findViewById(R.id.city_et);
searchBtn=findViewById(R.id.search_btn);
windTV=findViewById(R.id.wind_tv);
tempTV=findViewById(R.id.temp_tv);
weatherTV=findViewById(R.id.weather_tv);
}
}