Android项目之网络请求

本文介绍了一个基于Java的异步HTTP客户端框架AsyncHttp,该框架通过使用多线程处理GET和POST请求,支持延时请求、文件上传等功能,并提供了错误处理机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AsyncHttp框架

public class AsyncHttp {
    public static Handler handler = new Handler(Looper.getMainLooper());//回到主线程
    private static Executor executorServer = Executors.newCachedThreadPool();

    /**
     * 发起GET请求
     *
     * @param urlString        请求地址
     * @param iResponseHandler 请求回调
     */
    public static void get(final String urlString, final IResponseHandler iResponseHandler) {
        get(urlString, null, iResponseHandler);
    }

    /**
     * 发起get请求
     *
     * @param urlString        请求地址
     * @param params           参数
     * @param iResponseHandler 请求回调
     */
    public static void get(final String urlString, final Map<String, String> params,
                           final IResponseHandler iResponseHandler) {
        executorServer.execute(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection httpURLConnection = null;
                try {
                    String url;
                    if (params != null && params.size() > 0)
                        url = urlString + "?" + changeParams(params);//get方式为明文
                    else
                        url = urlString;
                    httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setConnectTimeout(10000);
                    httpURLConnection.setReadTimeout(15000);
                    httpURLConnection.addRequestProperty("Accept-Encoding", "gzip");//设置请求头

                    httpURLConnection.connect();

                    processResult(iResponseHandler, httpURLConnection);

                } catch (Exception exception) {
                    onError(iResponseHandler, exception);
                } finally {
                    if (httpURLConnection != null)
                        httpURLConnection.disconnect();
                }
            }

        });
    }

    private static void processResult(final IResponseHandler iResponseHandler,
                                      HttpURLConnection httpURLConnection) throws IOException {
        int code = httpURLConnection.getResponseCode();
        InputStream inputStream = getInputStream(httpURLConnection, code);
        byte[] data = IOUtils.readInputStream(inputStream);
        inputStream.close();

        onResult(iResponseHandler, code, data);
    }

    private static void onResult(final IResponseHandler iResponseHandler, final int code,
                                 final byte[] data) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                iResponseHandler.onResult(code, data);
            }
        });
    }

    private static void onError(final IResponseHandler iResponseHandler, final Exception exception) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                iResponseHandler.onError(exception);
            }
        });
    }

    private static InputStream getInputStream(HttpURLConnection httpURLConnection, int code)
            throws IOException {
        InputStream inputStream;
        if (code == HttpURLConnection.HTTP_OK)
            inputStream = httpURLConnection.getInputStream();
        else
            inputStream = httpURLConnection.getErrorStream();//获取错误信息的输入流

        String contentEncoding = httpURLConnection.getContentEncoding();
        if (contentEncoding != null && contentEncoding.contains("gzip"))//压缩方式
            inputStream = new GZIPInputStream(inputStream);
        return inputStream;
    }

    /**
     * 延时发起请求
     *
     * @param urlString        请求地址
     * @param params           参数
     * @param delay            延时时间
     * @param iResponseHandler 请求回调
     */
    public static void postDelay(final String urlString, final Map<String, String> params,
                                 int delay, final IResponseHandler iResponseHandler) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                post(urlString, params, iResponseHandler);
            }
        }, delay);
    }

    /**
     * application/x-www-form-urlencoded 方式 发起POST请求
     *
     * @param urlString        请求地址
     * @param params           参数
     * @param iResponseHandler 请求回调
     */
    public static void post(final String urlString, final Map<String, String> params,
                            final IResponseHandler iResponseHandler) {
        executorServer.execute(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection httpURLConnection = null;
                try {
                    httpURLConnection = getPostConnection(urlString,
                            "application/x-www-form-urlencoded; charset=UTF-8");
                    httpURLConnection.connect();

                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    if (params != null)
                        outputStream.write(changeParams(params).getBytes("UTF-8"));
                    outputStream.close();

                    processResult(iResponseHandler, httpURLConnection);
                } catch (Exception exception) {
                    onError(iResponseHandler, exception);
                } finally {
                    if (httpURLConnection != null)
                        httpURLConnection.disconnect();
                }
            }
        });
    }

    public static String changeParams(Map<String, String> params) {
        StringBuilder stringBuilder = new StringBuilder();
        boolean isFirst = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (!isFirst)
                stringBuilder.append("&");
            else
                isFirst = false;

            try {
                stringBuilder.append(entry.getKey()).append("=")
                        .append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 以application/octet-stream方式上传数据 post  二进制方式
     *
     * @param url              上传地址
     *                         数据
     * @param iResponseHandler 回调结果
     */
    public static void upload(final String url, final byte data[],
                              final IResponseHandler iResponseHandler, final OnProgressListener onProgressListener) {
        executorServer.execute(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection httpURLConnection = null;
                try {
                    httpURLConnection = getPostConnection(url, "application/octet-stream");
                    httpURLConnection.addRequestProperty("Content-length",
                            String.valueOf(data.length));
                    httpURLConnection.connect();

                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
                    IOUtils.copy(inputStream, outputStream, new OnProgressListenerOnUI(
                            onProgressListener, data.length));
                    outputStream.close();
                    inputStream.close();
                    processResult(iResponseHandler, httpURLConnection);
                } catch (Exception exception) {
                    onError(iResponseHandler, exception);
                } finally {
                    if (httpURLConnection != null)
                        httpURLConnection.disconnect();
                }
            }
        });
    }

    /**
     * 以application/octet-stream方式上传文件 post
     *
     * @param url              上传地址
     * @param file             文件
     * @param iResponseHandler 回调结果
     */
    public static void uploadFile(final String url, final File file,
                                  final IResponseHandler iResponseHandler, final OnProgressListener onProgressListener) {
        executorServer.execute(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection httpURLConnection = null;
                FileInputStream fileInputStream = null;
                try {
                    httpURLConnection = getPostConnection(url, "application/octet-stream");
                    httpURLConnection.addRequestProperty("Content-length",
                            String.valueOf(file.length()));
                    httpURLConnection.connect();

                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    fileInputStream = new FileInputStream(file);
                    IOUtils.copy(fileInputStream, outputStream, new OnProgressListenerOnUI(
                            onProgressListener, (int) file.length()));
                    outputStream.close();

                    processResult(iResponseHandler, httpURLConnection);
                } catch (Exception exception) {
                    onError(iResponseHandler, exception);
                } finally {
                    if (httpURLConnection != null)
                        httpURLConnection.disconnect();
                    IOUtils.close(fileInputStream);
                }
            }
        });
    }

    private static HttpURLConnection getPostConnection(final String url, String contentType)
            throws IOException {
        HttpURLConnection httpURLConnection;
        httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
        httpURLConnection.setRequestMethod("POST");//请求方式
        httpURLConnection.setDoInput(true);//设置输入输出
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setConnectTimeout(6000);//超时
        httpURLConnection.setReadTimeout(10000);
        httpURLConnection.setDefaultUseCaches(false);//连接缓存 再次连接时可能为缓存
        httpURLConnection.addRequestProperty("Content-Type", contentType);
        httpURLConnection.addRequestProperty("Accept-Encoding", "gzip");
        return httpURLConnection;
    }

    private static class OnProgressListenerOnUI implements OnProgressCallback {
        OnProgressListener onProgressListener;
        int length;
        long lastUpdateTime = System.currentTimeMillis();

        OnProgressListenerOnUI(OnProgressListener onProgressListener, int length) {
            super();
            this.onProgressListener = onProgressListener;
            this.length = length;
        }

        @Override
        public void onProgressChange(final int progress) {
            if (System.currentTimeMillis() - lastUpdateTime > 100 || length == progress) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (onProgressListener != null)
                            onProgressListener.onProgressChange(length, progress);
                    }
                });
                lastUpdateTime = System.currentTimeMillis();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值