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

HTTPConnection与JSON应用实例

2018-03-15 23:04 225 查看
JSON:一种轻量级的数据交换格式。

JSONObject:一个json对象,包含一对儿(Key/Value)数值,在Key和Value之间是以逗号”,”分隔。

JSONStringer:json文本构建类,每个JSONStringer实体只能对应创建一个JSON text。

JSONArray:它代表一组有序的数值。将其转换为String输出(toString)所表现的形式是用方括号包裹,数值以逗号”,”分隔。

JSONTokener:json解析类 ;

JSONException:json中用到的异常 。

HTTPConnection

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

查询天气步骤:

创建URL,定义StringBuffer数组;

通过URL得到HTTPConnection对象;

判断网络是否疏通;

创建输入流InPutStream、BufferedReader

创建一个数组用来接收数据,判断是否接收的到数据;

在onPostExecute里面,先判断网络网络是否受到阻碍;

如果网络通畅,解析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
4000
= 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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: