在Android中,我們常常需要向服務(wù)器請(qǐng)求數(shù)據(jù),并將從服務(wù)器獲取的數(shù)據(jù)展示給用戶。而HTTP通信中最常用的數(shù)據(jù)格式就是JSON。因此,我們需要使用Handler來(lái)發(fā)送JSON格式的數(shù)據(jù)。
// 創(chuàng)建一個(gè)Handler對(duì)象 Handler handler = new Handler(){ @Override public void handleMessage(Message msg){ super.handleMessage(msg); if(msg.arg1 == 0){ // 解析json數(shù)據(jù) try{ JSONObject jsonObject = new JSONObject(msg.obj.toString()); String name = jsonObject.getString("name"); int age = jsonObject.getInt("age"); }catch(JSONException e){ e.printStackTrace(); } } } }; // 創(chuàng)建一個(gè)線程并發(fā)送請(qǐng)求 new Thread(new Runnable(){ @Override public void run(){ try{ URL url = new URL("http://www.example.com/data.json"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder builder = new StringBuilder(); while((line = reader.readLine()) != null){ builder.append(line); } reader.close(); connection.disconnect(); // 將獲取到的json數(shù)據(jù)發(fā)送給Handler Message message = new Message(); message.arg1 = 0; message.obj = builder.toString(); handler.sendMessage(message); }catch(Exception e){ e.printStackTrace(); } } }).start();
上述代碼中,我們首先創(chuàng)建了一個(gè)Handler對(duì)象,并覆寫了它的handleMessage()方法,在handleMessage()方法中解析了從服務(wù)器獲取的JSON數(shù)據(jù)。接著,我們創(chuàng)建了一個(gè)線程,并發(fā)送HTTP請(qǐng)求獲取JSON數(shù)據(jù)。在獲取到JSON數(shù)據(jù)之后,我們將其封裝成Message對(duì)象,并通過(guò)Handler的sendMessage()方法發(fā)送給Handler。