您的位置:首页 > 理论基础 > 计算机网络

HttpURLConnection+JSON的使用实例

2018-03-15 18:26 543 查看

JSON

JSON是一种轻量级的数据交换格式,主要用于跟服务器进行交换数据。

JSON数据格式应用非常广泛,在APP开发中,大多数据端返回的接口数据都是采用JSON数据格式的。

JSON的两种数据格式

JSONObject和JSONArray,JSONObject表示JSON对象,而JSONArray表示的则是数组。

运用HttpURLConnection+JSON获取天气预报数据信息

代码如下

Activity中xml代码

<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.lenovo.liu.weatherdemo.MainActivity">

<EditText
android:id="@+id/weath_city"
android:layout_width="match_parent"
android:layout_height="50dp"
android:hint="请输入所要查询的城市" />

<Button
android:id="@+id/weather_btn"
android:layout_width="180dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:text="查询" />

<TextView
android:id="@+id/city_tx"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25dp"/>
<TextView
android:id="@+id/weather_tx"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25dp"/>
<TextView
android:id="@+id/temp_tx"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25dp"/>
<TextView
android:id="@+id/wind_tx"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25dp"/>

</LinearLayout>


Activity中代码

public class WeatherActivity extends AppCompatActivity {
//定义xml中所写的控件
private EditText cityEdit;
private Button weatherBtn;
//所选的城市
private TextView cityTv;
//所选城市的天气
private TextView weatherTv;
//城市温度
private TextView tempTv;
//城市的风向
private TextView windTv;
//定义一个String类型存放网站路径
private String num;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
bindID();//绑定id
//设置点击事件
weatherBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//获取所输入城市的名称
String city=cityEdit.getText().toString();
//存放和风天气所测城市的网站+城市
num="https://free-api.heweather.com/s6/weather/now?parameters&key=f79dae4784f446d0ac1405e197fd9254&location="+city;
//接收weatherTask传来的信息
WeatherTask weatherTask=new WeatherTask(WeatherActivity.this,cityTv,weatherTv,tempTv,windTv);
//启动异步任务
weatherTask.execute(num);
}
});
}
//绑定id的方法
private void bindID() {
cityEdit=findViewById(R.id.weath_city);
weatherBtn=findViewById(R.id.weather_btn);
cityTv=findViewById(R.id.city_tx);
weatherTv=findViewById(R.id.weather_tx);
tempTv=findViewById(R.id.temp_tx);
windTv=findViewById(R.id.wind_tx);
}
}


weatherTask类代码

//继承AsyncTask
public class WeatherTask extends AsyncTask<String,Integer,StringBuffer> {
private TextView cityTv;
private TextView weatherTv;
private TextView tempTv;
private TextView windTv;
private Context context;

//构造方法承接上下文
public WeatherTask(Context context,TextView cityTv,TextView weatherTv,TextView tempTv,TextView windTv){
this.context=context;
this.cityTv=cityTv;
this.weatherTv=weatherTv;
this.tempTv=tempTv;
this.windTv=windTv;
}
@Override
protected StringBuffer doInBackground(String... strings) {
//全局定义输出流
InputStream inputStream=null;
StringBuffer stringBuffer=null;
try {
//定义URL对象
URL url=new URL(strings[0]);
//发送http请求
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();

//判断网络是否异常,,若不等于200直接返回
if (httpURLConnection.getResponseCode()==200){
inputStream=httpURLConnection.getInputStream();
}
//创建输入流读取对象
a7fb

InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"UTF-8");
//输入流缓存读取
BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
stringBuffer=new StringBuffer();
//输入流转换成String
String iemp=null;
while ((iemp=bufferedReader.readLine())!=null){
stringBuffer.append(iemp);
}
//关闭输入流
bufferedReader.close();
inputStreamReader.close();
inputStream.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//返回所获取的路径
return stringBuffer;
}

@Override
protected void onPostExecute(StringBuffer stringBuffer) {
super.onPostExecute(stringBuffer);
String Json_str=stringBuffer.toString();

try {
//定义JSON数据
JSONObject hfobj=new JSONObject(Json_str);
JSONArray array=hfobj.getJSONArray("HeWeather6");
JSONObject locaobj1=array.getJSONObject(0).getJSONObject("basic");
String city=locaobj1.getString("parent_city");
JSONObject locaobj2=array.getJSONObject(0).getJSONObject("now");
String cond=locaobj2.getString("cond_txt");
String temp=locaobj2.getString("tmp");
String wind=locaobj2.getString("wind_dir");

cityTv.setText("地区:"+city);
weatherTv.setText("天气:"+cond);
tempTv.setText("温度:"+temp+"℃");
windTv.setText("风向:"+wind);

} catch (JSONException e) {
e.printStackTrace();
}
}
}


效果图如下

由于模拟器的原因只能使用拼音

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  获取JSON数据