public class Asny extends AsyncTask<String,Void,String> { //2.申明接口对象 private IcallBack icallBack; //3.传递一个接口实现类 public Asny(IcallBack icallBack) { this.icallBack = icallBack; } @Override protected String doInBackground(String... strings) { URL url= null; try { url = new URL(strings[0]); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setReadTimeout(5000); urlConnection.setConnectTimeout(5000); if(urlConnection.getResponseCode()==200) { InputStream inputStream = urlConnection.getInputStream(); String s = streamToString(inputStream); return s; } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); icallBack.getJson(s); } //1.定义接口 public interface IcallBack{ //只有申明,没有实现 void getJson(String jsonData); } /** * 将流转换成String * @param stream */ private String streamToString(InputStream stream) { StringBuilder sbuilder=new StringBuilder(); String str; BufferedReader reader=new BufferedReader(new InputStreamReader(stream)); try { while ((str=reader.readLine())!=null){ sbuilder.append(str); } } catch (Exception e) { e.printStackTrace(); } return sbuilder.toString(); }
}
//调用接口
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Asny asny = new Asny(new Asny.IcallBack() { @Override public void getJson(String jsonData) { Gson gson = new Gson(); Result result = gson.fromJson(jsonData, Result.class); List<Result.NewslistBean> newslist = result.getNewslist(); Log.i("TAG", "getJson: "+newslist.size()); ///关闭头尾布局 //plv.onRefreshComplete(); } }); asny.execute("http://api.tianapi.com/meinv/?key=11ea949d63cdcfc91838cb62177c0f00&num=10"); } }