簡單的工具類(判斷網路/網路資料/)
阿新 • • 發佈:2018-12-19
package com.example.news; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.google.gson.Gson; 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; import java.net.URLConnection; import java.util.List; //請求網路需要使用INTERNET許可權 //<uses-permission android:name="android.permission.INTERNET" /> //判斷網路型別需要使用ACCESS_NETWORK_STATE許可權 // <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> public class Uilts { //判斷網路是否有效 public static boolean isNetwork(Context context){ //獲取連線管理服務 ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); //得到連線狀態 NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); //不為空且以有效 return activeNetworkInfo!=null&&activeNetworkInfo.isAvailable(); } //判斷是否是手機網路 public static boolean isMobileNetwork (Context context){ //獲取連線管理服務 ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); //得到連線狀態 NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); //返回是否是手機網路 return activeNetworkInfo.getType()==ConnectivityManager.TYPE_MOBILE; } //定義請求網路資料方法 public static InputStream queryNetworkData(String s,Context context){ String string =""; try { //得到網路路徑 URL url = new URL(s); //開啟網路連線 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); //設定請求方式 urlConnection.setRequestMethod("GET"); //檢視是否是手機網路,如果是適當延長載入時間 boolean mobileNetwork = isMobileNetwork(context); int times; if(mobileNetwork){ times=10000; }else{ times=5000; } //讀取超時 urlConnection.setReadTimeout(times); //網路連線請求超時 urlConnection.setConnectTimeout(times); //得到連線返回碼,胖多是否請求成功 int responseCode = urlConnection.getResponseCode(); //判斷請求碼型別進行不同操作 switch (responseCode){ case 200: //請求成功,得到網路資料,解析資料得到集合 return urlConnection.getInputStream(); } } catch (java.io.IOException e) { e.printStackTrace(); } return null; } //將資料轉化為字串 ↓位元組流 public static String getString (InputStream is) { //字元流 InputStreamReader isr = new InputStreamReader(is); //字元緩衝流 BufferedReader br = new BufferedReader(isr); //建立一個可追加字串用來接收資料 StringBuilder builder = new StringBuilder(); //迴圈得到所有資料 try { for (String i = br.readLine();i!=null;i = br.readLine()){ builder.append(i); } } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } //Gson 解析 泛型 public static <E>E queryNewsLiatData(String s,Class clazz){ E e = (E)new Gson().fromJson(s,clazz); return e; } }