public class MainActivity extends AppCompatActivity { private ListView lv; private List<MenuInfo.ResultBean.DataBean.StepsBean> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv= (ListView) findViewById(R.id.listview); getData("http://apis.juhe.cn/cook/query.php"); } private void getData(String path){ new AsyncTask<String, Void, String>() { @Override protected void onPostExecute(String s) { super.onPostExecute(s); Gson gson=new Gson(); MenuInfo menu=gson.fromJson(s,MenuInfo.class); list=menu.getResult().getData().get(0).getSteps(); lv.setAdapter(new MyAdapter()); } @Override protected String doInBackground(String... strings) { try { String path=strings[0]; URL url=new URL(path); HttpURLConnection connection= (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); OutputStream os=connection.getOutputStream(); os.write("key=4866477692b8491f120e3608db277cb0&menu=红烧肉".getBytes()); os.flush(); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); int code=connection.getResponseCode(); if(code==200){ InputStream is=connection.getInputStream(); String json=StreamTools.readNetworks(is); return json; } } catch (Exception e) { e.printStackTrace(); } return null; } }.execute(path); } class MyAdapter extends BaseAdapter{ @Override public int getCount() { return list.size(); } @Override public Object getItem(int i) { return list.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder holder; if (view==null){ holder=new ViewHolder(); view=View.inflate(MainActivity.this,R.layout.items,null); holder.tvContent=view.findViewById(R.id.tvContent); view.setTag(holder); }else{ holder= (ViewHolder) view.getTag(); } holder.tvContent.setText(list.get(i).getStep()); return view; } } class ViewHolder{ TextView tvContent; } }
public class StreamTools { public static String readNetworks(InputStream is) throws Exception{ ByteArrayOutputStream baos=new ByteArrayOutputStream(); int len=0; byte[] buffer=new byte[1024]; while ((len=is.read(buffer))!=-1){ baos.write(buffer,0,len); } is.close(); baos.close(); return baos.toString(); } }