1. 程式人生 > >判斷網路使用

判斷網路使用

需要匯入一個許可權:
public static boolean isMobileNetwork(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.getType() == TYPE_MOBILE;
}
public String getRequest(String apiUrl) {//執行網路請求
String result = “”;
try {
URL url = new URL(apiUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(“GET”);
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
/if (isMobileNetwork()) {
urlConnection.setConnectTimeout(15000);
urlConnection.setReadTimeout(15000);
} else {
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
}

/
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
//網路通訊最少有兩個端: A B,它們之間通訊(交換資料)是通過I/O流來進行的:InputStream/OutputStream
result = stream2String(urlConnection.getInputStream());
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}