其他分享
首页 > 其他分享> > HttpUtil网络请求回调类

HttpUtil网络请求回调类

作者:互联网

public class HttpUtil {

    public interface HttpCallbackListener {

        void onFinish(String response);

        void one rror(Exception e);
    }

    private static CountDownLatch latch = null;//异步转同步

    public static void sendHttpRequest(final String address, final HttpCallbackListener listener) {

        latch = new CountDownLatch(1);
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    if (listener != null) {
                        // 回调onFinish()方法
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    if (listener != null) {
                        // 回调onError()方法
                        listener.onError(e);
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                    latch.countDown();
                }
            }
        }).start();
        try {
            latch.await();
        } catch (Exception e) {

        }
    }

}

标签:null,请求,public,listener,connection,new,回调,HttpUtil,response
来源: https://blog.csdn.net/zhen_apple/article/details/86680947