1. 程式人生 > >網路請求 + Json解析

網路請求 + Json解析

MainActivity 主頁面
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//第一步找控制元件
Button button= findViewById(R.id.button);
//第二步點選事件
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//第三步開啟子執行緒
new Thread(){
@Override
public void run() {
super.run();
//在這裡寫耗時操作(請求網路資料)
//第四步:判斷網路狀態
boolean networkConnected = Http.isNetworkConnected(MainActivity.this);
//判斷有沒有網
if (networkConnected){
//有網就請求資料
String get = Http.requestHttpGet(“

http://api.expoon.com/AppNews/getNewsList/type/1/p/1”);
Gson gson=new Gson();
JsonBean bean = gson.fromJson(get, JsonBean.class);
//把資料傳遞給主執行緒
Message message=new Message();
message.what=0;
message.obj=bean;
handler.sendMessage(message);
}else{
handler.sendEmptyMessageDelayed(1,0);
}

            }
        }.start();

        }
    });

}

Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
    switch (msg.what){
        case 0:
            JsonBean bean= (JsonBean) msg.obj;
            Toast.makeText(MainActivity.this,""+bean.toString(),Toast.LENGTH_LONG).show();

            break;
        case 1:
            //沒網就提示使用者 沒網
            Toast.makeText(MainActivity.this,"兄嘚,沒網啊?",Toast.LENGTH_LONG).show();
            break;
    }
    }
};

/**
* 判斷有沒有網
/
public static boolean isNetworkConnected(Context context) {
//注意要寫網路許可權
//判斷引數是否為空(必須)
if (context != null) {
//getSystemService 獲取系統服務
//獲取連線管理器
ConnectivityManager mConnectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
//獲取網路狀態
NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
if (info != null) {
//判斷網路是否可用
return info.isAvailable();
}
}
return false;
}
HTTP
/

*
* 請求資料GET請求
*/
public static String requestHttpGet(String strUrl) {

    try { //設定url
        URL url = new URL(strUrl);

        //獲取HttpURLConnection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //設定為get請求
        connection.setRequestMethod("GET");
        //設定連線主機超時時間
        connection.setConnectTimeout(5000);
        //設定從主機讀取資料超時
        connection.setReadTimeout(5000);
        //獲取請求碼(來判斷網路請求是否正確)
        int code = connection.getResponseCode();
        //判斷請求是否成功
        if (code == HttpURLConnection.HTTP_OK) {
            //如果資料請求成功
            //就獲取資料
            InputStream stream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "utf-8"));
            //拼接字串
            StringBuilder builder = new StringBuilder();
			
            //把資料讀取從成字串
            String str = "";
            while ((str = reader.readLine()) != null) {
                //把一行行資料拼接成一行資料
                builder.append(str);
            }
            //返回拼接後的資料
            return builder.toString();

        }
        //關閉連線
        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}