public class Utilgetdata {
public static void getdata(final String path, Context ct, final Myinterface inter){
if(NetWorkUtil.isConn(ct)){
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.setReadTimeout(5000);
connection.setConnectTimeout(5000);
int responseCode = connection.getResponseCode();
if (responseCode == 200){
InputStream inputStream = connection.getInputStream();
String json = streamToString(inputStream,"utf-8");
//json字符串已经获取到,,,也就是异步任务执行的结果获取到了
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
//返回的数据可以解析
inter.inter(s);
}
};
//调用
asyncTask.execute();
}else{NetWorkUtil.showNoNetWorkDlg(ct);}
}
private static String streamToString(InputStream inputStream, String charset) {
try {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charset);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String s = null;
StringBuilder builder = new StringBuilder();
while ((s = bufferedReader.readLine()) != null){
builder.append(s);
}
bufferedReader.close();
return builder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
public static void getdata(final String path, Context ct, final Myinterface inter){
if(NetWorkUtil.isConn(ct)){
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.setReadTimeout(5000);
connection.setConnectTimeout(5000);
int responseCode = connection.getResponseCode();
if (responseCode == 200){
InputStream inputStream = connection.getInputStream();
String json = streamToString(inputStream,"utf-8");
//json字符串已经获取到,,,也就是异步任务执行的结果获取到了
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
//返回的数据可以解析
inter.inter(s);
}
};
//调用
asyncTask.execute();
}else{NetWorkUtil.showNoNetWorkDlg(ct);}
}
private static String streamToString(InputStream inputStream, String charset) {
try {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charset);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String s = null;
StringBuilder builder = new StringBuilder();
while ((s = bufferedReader.readLine()) != null){
builder.append(s);
}
bufferedReader.close();
return builder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}