HttpURLConnection + Handler

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_43301984/article/details/83380091
public class URLTools {
    public URLTools() {
    }

    ;

    public URLTools get(final String path) {
        new Thread() {

            private HttpURLConnection httpURLConnection;

            @Override
            public void run() {
                super.run();
                try {
                    URL url = new URL(path);
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setConnectTimeout(3000);
                    int responseCode = httpURLConnection.getResponseCode();
                    if (responseCode == 200) {
                        InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8");
                        String s = CharStreams.toString(inputStreamReader);
                        Message message = Message.obtain();
                        message.obj = s;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
        return this;
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String obj = (String) msg.obj;
            data.getName(obj);
        }
    };

    private HttpData data;

    public void getData(HttpData data) {
        this.data = data;
    }

    public interface HttpData {
        void getName(String name);
    }
}

 

展开阅读全文

没有更多推荐了,返回首页