new Thread() { @Override public void run() { super.run(); try { // 设置访问的路劲,相当于在浏览器输入网址 URL url = new URL("http://apis.juhe.cn/cook/query.php?menu=秘制红烧肉&
key=6666666666666"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置访问的时间 connection.setConnectTimeout(5000); // 设置读取的时间 connection.setReadTimeout(5000); // 设置访问方式,GET和POST 必须大写 connection.setRequestMethod("GET"); // 得到回传码 int code = connection.getResponseCode(); // 回传码200代表成功 if (code == 200) { // 访问成功以后得到回传的内容,io流 InputStream is = connection.getInputStream(); // 调用io流读取数据,下面的方法是自定义类,new ByteArrayOutputStream() String json = GetUtils.GetString(is); Gson gson = new Gson(); Bean caipu = gson.fromJson(json, Bean.class); List<Bean.ResultBean.DataBean.StepsBean> steps = caipu.getResult().getData().get(0).getSteps(); for (Bean.ResultBean.DataBean.StepsBean st : steps ) { System.out.println("制作步骤:" + st.getStep().toString()); } } } catch (Exception e) { e.printStackTrace(); } } }.start();
public class GetUtils { public static String GetString(InputStream is) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] b=new byte[1024]; while (true){ int m = is.read(b); if (m ==-1) { break; } bos.write(b,0,m); } return bos.toString(); } catch (IOException e) { e.printStackTrace(); } return null; } }