public class MainActivity extends AppCompatActivity {
String urldata="http://api.tianapi.com/huabian/?key=48a7d7193e11bd2dd4a683b6e2f90a4f&num=10"; private ListView lv;@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = findViewById(R.id.lv); mytask mk = new mytask(); mk.execute(); } class mytask extends AsyncTask<String,Void,String>{@Override
protected String doInBackground(String... strings) { try { URL url=new URL(urldata); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setReadTimeout(5000); urlConnection.setConnectTimeout(5000); if (urlConnection.getResponseCode()==200){ InputStream inputStream = urlConnection.getInputStream(); return steamstring(inputStream); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }//执行网络任务之后的请求,,更新UI @Override protected void onPostExecute(String s) { super.onPostExecute(s); Gson gson = new Gson(); GetData getData = gson.fromJson(s, GetData.class); Myadapter myadapter = new Myadapter(MainActivity.this, getData.getNewslist()); lv.setAdapter(myadapter); } } public String steamstring(InputStream inputStream ){ StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String str; try { while((str=reader.readLine())!=null){ builder.append(str); }} catch (IOException e) {
e.printStackTrace(); } return builder.toString(); }}