zoukankan      html  css  js  c++  java
  • 网络编程最佳实践一

    HttpUtil.java

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    
    /**
     * Created by 王德强 on 2017/7/25.
     */
    
    public class HttpUtil{
        public static void sendHttpRequest(final String address,final HttpCallbackListener listener){
            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.setReadTimeout(8000);
                        connection.setConnectTimeout(8000);
                        connection.setDoOutput(true);
                        connection.setDoInput(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){
                            listener.onFinish(response.toString());
                        }
                    } catch (Exception e) {
                        if(listener!=null){
                            listener.onError(e);
                        }
                    }finally {
                        if(connection!=null){
                            connection.disconnect();
                        }
                    }
                }
            }).start();
        }

    回调机制 接口
    HttpCallbackListener.interfac

    
    interface HttpCallbackListener {
        void onFinish(String response);
        void onError(Exception e);
    }
    

    以后每当需要发起一条Http请求的时候就可以这样写:

    String address = "http://www.baidu.com";
    String response = HttpUtil.sendHttpRequest(address);
  • 相关阅读:
    运动世界校园破解2.0
    Docker进阶操作
    一键开启https
    Docker的第一次实践总结
    手机通话黑屏
    mysql安装、操作、配置、远程
    excel添加列数据导入后,列数据不显示的问题
    常见邮箱的各类协议服务器地址
    POP3/SMTP/IMAP等邮箱协议的基本概念
    You credentials did not work (The logon attempt failed)
  • 原文地址:https://www.cnblogs.com/CCCrunner/p/11781929.html
Copyright © 2011-2022 走看看