package com.my.gethttpjsondata; import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.io.InputStre ...
package com.my.gethttpjsondata;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView textView;
static String err;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.tv_json);
}
public void Click1(View view)
{
//Toast.makeText(MainActivity.this, "開始", 0).show();
//String path="http://192.168.1.151:10080/?module={appId:%22d1%22,id:%22getAllUser%22}";
try {
//textView.setText(getJsonContent(path));
//String r=getJsonContent(path);
//Toast.makeText(MainActivity.this, r, 0).show();
// 開啟一個子線程,進行網路操作,等待有返回結果,使用handler通知UI
new Thread(networkTask).start();
/**
List<Map> list=new ArrayList<Map>();
list=getJSONObject(path,MainActivity.this);
for (Map list2 : list) {
String id = list2.get("UserID").toString();
String name = list2.get("UserName").toString();
Toast.makeText(MainActivity.this, "id:" + id + " | name:" + name, 0).show();
}
**/
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), 0).show();
e.printStackTrace();
}
}
/**
* 網路操作相關的子線程
*/
Runnable networkTask = new Runnable() {
@Override
public void run() {
String path="http://192.168.1.151:10080/?module={appId:%22d1%22,id:%22getAllUser%22}";
List<Map> list=new ArrayList<Map>();
try {
list=getJSONObject(path);
} catch (Exception e) {
e.printStackTrace();
}
for (Map list2 : list) {
String id = list2.get("UserID").toString();
String name = list2.get("UserName").toString();
Log.v("data", "id:" + id + " | name:" + name);
}
}
};
public static List<Map> getJSONObject(String path) throws Exception {
List<Map> list = new ArrayList<Map>();
Map map = null;
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection對象,我們可以從網路中獲取網頁數據.
conn.setConnectTimeout(5 * 1000); // 單位是毫秒,設置超時時間為5秒
conn.setRequestMethod("GET"); // HttpURLConnection是通過HTTP協議請求path路徑的,所以需要設置請求方式,可以不設置,因為預設為GET
//Log.v("abc", "Status:"+conn.getResponseCode());
if (conn.getResponseCode() == 200) {// 判斷請求碼是否是200碼,否則失敗
InputStream is = conn.getInputStream(); // 獲取輸入流
byte[] data = readStream(is); // 把輸入流轉換成字元數組
String json = new String(data); // 把字元數組轉換成字元串
//數據形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小豬"},{"id":2,"name":"小貓"}]}
JSONObject jsonObject=new JSONObject(json); //返回的數據形式是一個Object類型,所以可以直接轉換成一個Object
//int total=jsonObject.getInt("total");
Boolean success=jsonObject.getBoolean("success");
//Log.i("abc", "total:" + total + " | success:" + success); //測試數據
JSONArray jsonArray = jsonObject.getJSONArray("data");//裡面有一個數組數據,可以用getJSONArray獲取數組
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject item = jsonArray.getJSONObject(i); // 得到每個對象
int id = item.getInt("UserID"); // 獲取對象對應的值
String name = item.getString("UserName");
map = new HashMap(); // 存放到MAP裡面
map.put("UserID", id + "");
map.put("UserName", name);
list.add(map);
}
}
// ***********測試數據******************
for (Map list2 : list) {
String id = list2.get("UserID").toString();
String name = list2.get("UserName").toString();
Log.v("data", "id:" + id + " | name:" + name);
}
return list;
}
public static byte[] readStream(InputStream inputStream) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
bout.write(buffer, 0, len);
}
bout.close();
inputStream.close();
return bout.toByteArray();
}
public void Click2(View view)
{
Thread th=new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
String httpUrl = "http://apis.baidu.com/heweather/weather/free";
String httpArg = "city=beijing";
String jsonResult = request(httpUrl, httpArg);
Log.v("jsonResult",jsonResult);
//Toast.makeText(MainActivity.this, jsonResult, 0).show();
}
});
th.start();
}
/**
* @param urlAll
* :請求介面
* @param httpArg
* :參數
* @return 返回結果
*/
public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
httpUrl = httpUrl + "?" + httpArg;
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
// 填入apikey到HTTP header
connection.setRequestProperty("apikey", "574cc9baa2b89769d89a6799c194f806");
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
Log.v("dituerr", e.toString());
e.printStackTrace();
}
return result;
}
}
下載地址:http://files.cnblogs.com/files/qujian15/GetHttpJsonData.rar