//必须加的权限<uses-permission android:name="android.permission.INTERNET"></uses-permission>
//实例必须在主线程中
new MAsycnJson().execute(path);
//创建的AsycnTask类
class MAsycnJson extends AsyncTask<String,Void,String>{
//子线程中运行的方法
@Override protected String doInBackground(String... strings) { //调用请求网络的方法
return new Util().getString(strings[0]); }
//主线程中运行(解析Json并更新UI) @Override protected void onPostExecute(String s) { super.onPostExecute(s); Gson gson = new Gson(); Yk09 yk09 = gson.fromJson(s, Yk09.class); listview = yk09.getData().getIndexrecommend().getListview(); list.addAll(listview); pAdapter.notifyDataSetChanged(); plv.onRefreshComplete(); }}
//请求网络的工具类public class Util { //获取String数据 public String getString(String urlString){ try { //实例化URL对象 URL url = new URL(urlString); //调用方法 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); //获取响应码 int responseCode = urlConnection.getResponseCode(); //判断响应码 if (responseCode==200) { //获取输入流 InputStream inputStream = urlConnection.getInputStream(); //获取字符输入流 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); //实例化StringBuffer对象 StringBuffer stringBuffer = new StringBuffer(); //定义空字符 String str=""; //循环读取 while((str=bufferedReader.readLine())!=null){ //拼接字符 stringBuffer.append(str); } //返回String return stringBuffer.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }
AsycnTack与URLConnection的结合
最新推荐文章于 2023-06-01 23:20:01 发布