AsyncTask
程序员文章站
2022-04-25 15:49:31
...
private void Task() {
final String path="http://www.xieast.com/api/news/news.php?type=top&page="+page;
new AsyncTask<String,Void,List<Bean.DataBean>>(){
@Override
protected List<Bean.DataBean> doInBackground(String... strings) {
String s=HttpUrl.getHttp(strings[0]);
Bean json = new Gson().fromJson(s, Bean.class);
return json==null?null:json.getData();
}
@Override
protected void onPostExecute(List<Bean.DataBean> dataBeans) {
super.onPostExecute(dataBeans);
if(dataBeans==null){
Toast.makeText(getActivity(),"请求数据失败",Toast.LENGTH_LONG).show();
return;
}
initUpdrand();
updateed(dataBeans);
}
}.execute(path);
}
private void updateed(List<Bean.DataBean> dataBeans) {
if(page==1){
adpater.setData(dataBeans);
}else{
adpater.getData(dataBeans);
}
}
private void initUpdrand() {
page++;
xlv.stopLoadMore();
xlv.stopRefresh();
}
HttpUrl
public class HttpUrl {
public static String getHttp(String string) {
try {
URL url = new URL(string);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
int code = urlConnection.getResponseCode();
if(code==200){
String result=String2(urlConnection.getInputStream());
return result;
}
} catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String String2(InputStream inputStream) throws IOException {
StringBuffer sb = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String s;
while((s=reader.readLine())!=null){
sb.append(s);
}
reader.close();
return sb.toString();
}
}