这是一种简单的方法
/**
* 获取URL中字符串
*
* @param url 网址字符串
* @return String 服务端存储字符串
*/
public String getHttpsContent(String url) {
//利用java Scanner从URL读取Content
String httpsContent = null;
try {
Scanner scanner = new Scanner(new URL(url).openStream(), StandardCharsets.UTF_8.toString());
scanner.useDelimiter("\\A");
if (scanner.hasNext()) {
httpsContent = scanner.next();
}
scanner.close();
} catch (Exception exception) {
exception.printStackTrace();
}
if (httpsContent != null) {
Log.i(getClass().toString() + "//getHttpsContent()", httpsContent);
}
return httpsContent;
}
在这之前可以判断一下网络通不通
/**
* 是否联网
*
* @param context ()
* @return boolean 是否联网
*/
public boolean isNetworkAvailable(Context context) {
if (context != null) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected()) {
Log.d(getClass().toString() + "//isNetworkAvailable()", "TRUE");
return true;
}
}
Log.d(getClass().toString() + "//isNetworkAvailable()", "FALSE");
return false;
}
调用的时候判断一下连上网没有然后进行数据处理
if (isNetworkAvailable(getApplicationContext())) {
do_something();
} else {
Toast.makeText(getBaseContext(), "网络不可用", Toast.LENGTH_SHORT).show();
}
注意:网络方面的处理一定一定一定放在子线程处理,避免anr
new Thread(() -> {
Looper.prepare();
if (isNetworkAvailable(getApplicationContext())) {
do_something();
}
} else {
Toast.makeText(getBaseContext(),"网络不可用" , Toast.LENGTH_SHORT).show();
}
Looper.loop();
}).start();
|