关于本篇博客讲的是HttpURLConnection网络请求与JSON结合使用请求天气预报的例子,
首先,先来了解一下JSON(关于HttpURLConnection详见前三篇博客):
JSON,全称是 JavaScript Object Notation,即 JavaScript 对象标记法。这是一种 轻量级 (Light-Weight)、 基于文本的 (Text-Based)、 可读的 (Human-Readable)格式。
JSON格式有两个显著的优点:书写简单,一目了然;JSON 无论对于人,还是对于机器来说,都是十分便于阅读和书写的,而且相比 XML 文件更小;JSON 格式的创始人声称此格式永远不升级,这就表示这种格式具有长时间的稳定性;
1.JSON对值的类型和格式有严格的规定
复合类型的值只能是数组或对象,不能是函数、正则表达式对象、日期对象。
简单类型的值只有四种:字符串、数值(必须以十进制表示)、布尔值和null(不能使用NaN, Infinity, -Infinity和undefined)。
字符串必须使用双引号表示,不能使用单引号。
对象的键名必须放在双引号里面。
数组或对象最后一个成员的后面,不能加逗号。
PS: 需要注意的是,空数组和空对象都是合格的JSON值,null本身也是一个合格的JSON值。
2.JSON 的语法规则
JSON 的语法规则十分简单,可称得上“优雅完美”,总结起来有:
数组(Array)用方括号(“[]”)表示。
对象(Object)用大括号(”{}”)表示。
名称/值对(name/value)组合成数组和对象。
名称(name)置于双引号中,值(value)有字符串、数值、布尔值、null、对象和数组。
并列的数据之间用逗号(“,”)分隔。
接下来请看天气预报实例:
效果图:
1.首先,创建Activity,布置其xml代码:
<?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.test.project.jsondate.Weather1Activity">
<EditText
android:id="@+id/city_et"
android:layout_width="match_parent"
android:layout_height="50dp"
android:hint="请输入城市"
/>
<Button
android:id="@+id/search_Btn"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="20sp"
android:text="搜索"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="60dp"
android:layout_height="40dp"
android:id="@+id/tv1"
android:text="温度:"
/>
<TextView
android:layout_width="60dp"
android:layout_height="40dp"
android:id="@+id/tv2"
android:layout_below="@+id/tv1"
android:text="天气:"
/>
<TextView
android:layout_width="60dp"
android:layout_height="40dp"
android:id="@+id/tv3"
android:layout_below="@+id/tv2"
android:text="风力:"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="@+id/wendu_tv"
android:textSize="20sp"
android:layout_toRightOf="@+id/tv1"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="@+id/weather_tv"
android:textSize="20sp"
android:layout_toRightOf="@+id/tv2"
android:layout_below="@+id/tv1"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="@+id/wind_tv"
android:textSize="20sp"
android:layout_toRightOf="@+id/tv3"
android:layout_below="@+id/tv2"
/>
</RelativeLayout>
</LinearLayout>
Java代码:
package com.test.project.jsondate;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
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 Weather1Activity extends AppCompatActivity {
private EditText cityET;
private Button button;
private TextView windtv;
private TextView wendutv;
private TextView weathertv;
private String API="https://free-api.heweather.com/s6/weather/now?key=389b98d2fe6e402483428f6510250c3d&location=";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather1);
bindId();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String city=cityET.getText().toString();
new Mytask().execute(API+city);
}
});
}
class Mytask extends AsyncTask<String,Integer,String>{
@Override
protected String doInBackground(String... strings) {
StringBuffer stringBuffer=null;
try {
URL url=new URL(strings[0]);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
InputStream inputStream=httpURLConnection.getInputStream();
InputStreamReader reader=new InputStreamReader(inputStream,"UTF-8");
BufferedReader bufferedReader=new BufferedReader(reader);
stringBuffer=new StringBuffer();
String temp=null;
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);
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);
wendutv.setText(temp);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void bindId() {
cityET=findViewById(R.id.city_et);
button=findViewById(R.id.search_Btn);
windtv=findViewById(R.id.wind_tv);
wendutv=findViewById(R.id.wendu_tv);
weathertv=findViewById(R.id.weather_tv);
}
}