频道栏目
首页 > 资讯 > 其他 > 正文

封装AsyncTask成工具类的使用方法

18-07-31        来源:[db:作者]  
收藏   我要投稿

先说一下怎么使用:

String s = new GetAsyncTaskData() {}.execute("http://169.254.168.158/mobile/index.phpact=goods&op=goods_list&page=100").get();

接着再去Gson解析就好了,但是下面的代码会等到网络获取到数据之后再进行。

public class GetNetData {
 public static String getData(String path){
  String result = null;
  try {
URL url=new URL(path);
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
int code=conn.getResponseCode();
Log.i("-----------", "getData: "+code);
if (code==200){
 InputStream is=conn.getInputStream();
 ByteArrayOutputStream baos=new ByteArrayOutputStream();
 int len=-1;
 byte[] buff=new byte[1024];
 while ((len=is.read())!=-1){
  baos.write(buff,0,len);
 }
 result=new String(baos.toByteArray());
}
  } catch (Exception e) {
e.printStackTrace();
  }
  return result;
 }
}
public class GetAsyncTaskData extends AsyncTask {
 @Override
 protected String doInBackground(String... strings) {
  String result=GetNetData.getData(strings[0]);
  return result;
 }
 
 @Override
 protected void onPostExecute(String s) {
  super.onPostExecute(s);
 }
}
相关TAG标签
上一篇:SQL语句下groupby,having的用法解析
下一篇:MySql创建、授权、删除用户的操作示范总结
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站