017-获取线程中run()里的数据

public class  newThread extends Thread  {
    private String msg;

    public void run(){
        //第一步:实例化URL对象
        String address="https://api.heclouds.com/devices/584758432/datastreams/dust_concentration"; //查询最新数据流详情
//      String address="https://api.heclouds.com/devices/584758432/datapoints?limit=10"; //查询历史数据
//      String address="https://api.heclouds.com/devices/584758432/datastreams/dust_concentration"; //查询数据流详情

        try {
            URL url =new URL(address);   //实例化URL对象
            //实例化 HttpURLConnection对象
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置链接属性
            conn.setRequestMethod("GET");//设置请求方法
            conn.setRequestProperty("api-key","TeO0juJlw1uDTmDJRKD7cvzj=cM=");
            conn.setRequestProperty("Host","api.heclouds.com");
            conn.setReadTimeout(5000);//设置超时时间
            if(conn.getResponseCode()==200){ //获取状态码 200表示连接成功
                //获取输入流
                InputStream in= conn.getInputStream();
                //读取输入流
                byte[] b=new byte[1024*512]; //定义一个byte数组读取输入流
                ByteArrayOutputStream baos = new ByteArrayOutputStream(); //定义缓存流来保存输入流的数据
                int len;
                while((len=in.read(b))>-1){  //每次读的len>-1 说明是是有数据的
                    baos.write(b,0,len);  //三个参数  输入流byte数组   读取起始位置  读取终止位置
                }
                msg=baos.toString();
                Log.e("TAG", msg);
//                System.out.println("test"+msg);
            }
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }

    }
  // 返回数据
public static String data() { newThread thread = new newThread(); thread.start(); while (thread.msg == null) { try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("test" + thread.msg); return thread.msg; } }
原文地址:https://www.cnblogs.com/qiuniao/p/12320579.html