美文网首页
Android——发送Http请求

Android——发送Http请求

作者: 四喜汤圆 | 来源:发表于2019-10-08 21:40 被阅读0次

    一、作用

    Android 发送 Http 请求一般有两种方式:HttpURLConnection、HttpClient,由于 HttpClient API 数量过多、扩展困难等问题,Android 官方推荐 HttpURLConnection。

    二、概念

    三、使用

    1. 简单使用

    (1) 获取 HttpURLConnection 实例

    (2)设置请求方法

    (3)自由定制

    (4)向服务端携带参数

    (5)读取服务端传过来的数据

    URL url = null;
    
    HttpURLConnection connection = null;
    
    try {
        url = new URL(address);
        // 1,得到HttpURLConnection 实例
        connection = (HttpURLConnection) url.openConnection();
        // 2,设置请求方法
        connection.setRequestMethod("GET");
        // 3,自由定制:连接超时、读取超时等
        connection.setConnectTimeout(8000);
        connection.setReadTimeout(8000);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        // 4,向服务器发送数据
        //            connection.setRequestMethod("POST");
        //            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        //            out.writeBytes("username=hh&pwd=12345");
        // 5,得到服务器返回数据
        InputStream inputStream = connection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            response.append(line);
        }
        return response.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    

    2.功能封装

    String sendHttpRequestGet1(String address)中,如果我们直接在该方法中开启线程进行 Http 请求,那么服务端的响应数据是无法返回的,所有耗时逻辑都在子线程中执行,该方法会在服务器还没来得及响应的时候就执行结束了,自然也无法返回响应的数据。

    public static String sendHttpRequestGet1(String address) {
        URL url = null;
        HttpURLConnection connection = null;
    
        try {
            url = new URL(address);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(8000);
            connection.setReadTimeout(8000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            // 得到服务器返回数据
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    

    此时借助 Java 的回调机制,将服务器响应的数据传入onFinish()中,异常时将异常原因传入到onError()中。

    public static void sendHttpRequestGet2(final String address, final HttpCallbackListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url = null;
                HttpURLConnection connection = null;
    
                try {
                    url = new URL(address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    // 得到服务器返回数据
                    InputStream inputStream = connection.getInputStream();
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        response.append(line);
                    }
                    if (listener != null) {
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (listener != null) {
                        listener.onError(e);
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        });
    
    }
    
    public interface HttpCallbackListener {
        void onFinish(String response);
    
        void onError(Exception e);
    }
    

    相关文章

      网友评论

          本文标题:Android——发送Http请求

          本文链接:https://www.haomeiwen.com/subject/tmjipctx.html