public class NetDataUtil {
public static void getData(Context content, final String path, final JsonStringCallaBack callsback){
//调用网络操作的工具类,判断网络是否可用,可用的话访问网络数据
if (NetWorkUtil.isConn(content)){
Toast.makeText(content,"网络正常",Toast.LENGTH_SHORT).show();
//异步访问网络
AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
try {
//将字符串路径存放到网络路径
URL url = new URL(path);
//打开网络地址
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置请求方式
connection.setRequestMethod("GET");
//设置连接超时
connection.setConnectTimeout(10000);
//设置读取超时
connection.setReadTimeout(10000);
//获得状态码
int responseCode = connection.getResponseCode();
//如果请求成功的话返回的状态码是200,进行判断是否请求成功
if (responseCode==200){
InputStream inputStream = connection.getInputStream();
//字节流到字符串的转换,这里抽取成了方法,调用自己的方法,得到是转换完的字符串
String json = streamToString(inputStream, "utf-8");
if (json!=null){
return json;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
//callsback为接口变量,存到接口,谁实现接口谁去解析
callsback.getJsonData(s);
}
};
//执行
asyncTask.execute();
}else{
NetWorkUtil.showNoNetWorkDlg(content);
}
}
//字节流转换字符串的方法
private static String streamToString(InputStream inputStream, String charset) {
try {
//转换流,将字节流转字符串,并转换编码
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
//字符缓冲流
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//字符串缓冲区
StringBuilder stringBuilder = new StringBuilder();
//
String len = null;
//按行读
while((len=bufferedReader.readLine())!=null){
//追加到字符串缓冲区存放
stringBuilder.append(len);
}
//将字符串返回
return stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
异步访问网络数据工具类
最新推荐文章于 2024-06-28 02:45:42 发布