package com.example.administrator.myday_09; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ListView; import com.example.myday_09.R; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; public class MainActivity extends AppCompatActivity { private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.list_view); getDataFromNet(); } private void getDataFromNet() { AsyncTask<Void,Void,String> asyncTask = new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... voids) { try { URL url = new URL("http://v.juhe.cn/weixin/query?key=88f7bbc507e3ecacfaeab2b47dd8936f&ps=30"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); int responsecode = connection.getResponseCode(); if(responsecode == 200){ InputStream inputStream = connection.getInputStream(); String json = streamToString(inputStream,"utf-8"); return json; } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { Gson gson = new Gson(); DataDataBean dataDataBean = gson.fromJson(s, DataDataBean.class); List<DataDataBean.ResultBean.ListBean> list = dataDataBean.getResult().getList(); MyAdapter myAdapter = new MyAdapter(MainActivity.this,list); listView.setAdapter(myAdapter); } }; asyncTask.execute(); } private String streamToString(InputStream inputStream, String charset){ try { InputStreamReader reader = new InputStreamReader(inputStream,charset); BufferedReader bufferedReader = new BufferedReader(reader); String s = null; StringBuffer stringBuffer = new StringBuffer(); while((s = bufferedReader.readLine()) != null){ stringBuffer.append(s); } bufferedReader.close(); return stringBuffer.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } }