其他分享
首页 > 其他分享> > Android的网络请求之HttpURLConnection封装

Android的网络请求之HttpURLConnection封装

作者:互联网

HttpURLConnection封装

OkHttp的封装已经很好了,但是有时候在调用第三方的时候,还是需要自己来处理一下,因此简单封装,便于后面的使用。
public class HttpUtil {
    private static final int CONNECT_TIME_OUT = 15000;
    private static final int READ_TIME_OUT = 20000;

    /**
     * 将请求的内容转为 url?a=b&i=j&c=d
     *
     * @param url      请求的前缀
     * @param paramMap 请求的参数
     * @return
     */
    public static String formatUrlWithParas(String url, Map<String, String> paramMap) {
        StringBuilder urlWithParas = new StringBuilder(isEmpty(url) ? "" : url);
        String paras = joinParas(paramMap);
        if (!isEmpty(paras)) {
            urlWithParas.append("?").append(paras);
        }
        return urlWithParas.toString();
    }

    /**
     * 将请求的内容转为 url?a=b&i=j&c=d
     *
     * @param url      请求的地址
     * @param paramMap 请求的参数
     * @return
     */
    public static String formatEncodeUrlWithParas(String url, Map<String, String> paramMap) {
        StringBuilder urlWithParas = new StringBuilder(isEmpty(url) ? "" : url);
        String paras = joinParas(paramMap);
        if (!isEmpty(paras)) {
            urlWithParas.append("?").append(paras);
        }
        return urlWithParas.toString();
    }


    /**
     * Http的请求
     *
     * @param url       请求的地址
     * @param headerMap 请求头集合
     * @return 请求返回的字节数据
     */
    public static byte[] getRequest(String url, Map<String, String> headerMap) {
        return httpsRequest(url, "GET", headerMap, "", 0, CONNECT_TIME_OUT, READ_TIME_OUT, null);
    }

    /**
     * Http的请求
     *
     * @param url        请求的地址
     * @param headerMap  请求头集合
     * @param reqContent 请求体的内容
     * @return 请求返回的字节数据
     */
    public static byte[] postRequest(String url, Map<String, String> headerMap, byte[] reqContent) {
        return httpsRequest(url, "POST", headerMap, "", 0, CONNECT_TIME_OUT, READ_TIME_OUT, reqContent);
    }

    /**
     * Http的请求
     *
     * @param url            请求的地址
     * @param method         请求方法
     * @param headerMap      请求头集合
     * @param connectTimeout 连接时间
     * @param readTimeout    读取时间
     * @param reqContent     请求体的内容
     * @return 请求返回的字节数据
     */
    public static byte[] httpRequest(String url, String method, Map<String, String> headerMap,
                                     int connectTimeout, int readTimeout, byte[] reqContent) {
        return httpsRequest(url, method, headerMap, "", 0, connectTimeout, readTimeout, reqContent);
    }

    /**
     * Http的请求
     *
     * @param url            请求的地址
     * @param method         请求方法
     * @param headerMap      请求头集合
     * @param proxyHost      代理主机
     * @param proxyPort      代理端口
     * @param connectTimeout 连接时间
     * @param readTimeout    读取时间
     * @param reqContent     请求体的内容
     * @return 请求返回的字节数据
     */
    public static byte[] httpRequest(String url, String method, Map<String, String> headerMap, String proxyHost, final int proxyPort,
                                     int connectTimeout, int readTimeout, byte[] reqContent) {
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            URL serverUrl = new URL(url);
            if (!isEmpty(proxyHost) && proxyPort != 0) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
                urlConnection = (HttpURLConnection) (serverUrl.openConnection(proxy));
            } else {
                urlConnection = (HttpURLConnection) (serverUrl.openConnection());
            }
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setRequestMethod(method);
            urlConnection.setConnectTimeout(connectTimeout);
            urlConnection.setReadTimeout(readTimeout);
            if (headerMap != null && headerMap.size() > 0) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            //封装的请求头 urlConnection.getRequestProperties();
            if (reqContent != null && reqContent.length > 0) {
                //需要写数据到请求体中 因为默认是GET请求,所以
                urlConnection.setDoOutput(true);
                OutputStream outputStream = urlConnection.getOutputStream();
                outputStream.write(reqContent);
                outputStream.flush();
                outputStream.close();
            }
            //getInputStream()会隐式的调用urlConnection.connect() 并将请求体上传至服务器
            inputStream = urlConnection.getInputStream();
            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                //返回的请求头 urlConnection.getHeaderFields();
                return IOUtil.readInputStream(inputStream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtil.close(inputStream);
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
        return null;
    }

    /**
     * Https的请求
     *
     * @param url       请求的地址
     * @param headerMap 请求头集合
     * @return 请求返回的字节数据
     */
    public static byte[] httpsGetRequest(String url, Map<String, String> headerMap) {
        return httpsRequest(url, "GET", headerMap, "", 0, CONNECT_TIME_OUT, READ_TIME_OUT, null);
    }

    /**
     * Https的请求
     *
     * @param url        请求的地址
     * @param headerMap  请求头集合
     * @param reqContent 请求体的内容
     * @return 请求返回的字节数据
     */
    public static byte[] httpsPostRequest(String url, Map<String, String> headerMap, byte[] reqContent) {
        return httpsRequest(url, "POST", headerMap, "", 0, CONNECT_TIME_OUT, READ_TIME_OUT, reqContent);
    }

    /**
     * Https的请求
     *
     * @param url            请求的地址
     * @param method         请求方法
     * @param headerMap      请求头集合
     * @param connectTimeout 连接时间
     * @param readTimeout    读取时间
     * @param reqContent     请求体的内容
     * @return 请求返回的字节数据
     */
    public static byte[] httpsRequest(String url, String method, Map<String, String> headerMap,
                                      int connectTimeout, int readTimeout, byte[] reqContent) {
        return httpsRequest(url, method, headerMap, "", 0, connectTimeout, readTimeout, reqContent);
    }

    /**
     * Https的请求
     *
     * @param url            请求的地址
     * @param method         请求方法
     * @param headerMap      请求头集合
     * @param proxyHost      代理主机
     * @param proxyPort      代理端口
     * @param connectTimeout 连接时间
     * @param readTimeout    读取时间
     * @param reqContent     请求体的内容
     * @return 请求返回的字节数据
     */
    public static byte[] httpsRequest(String url, String method, Map<String, String> headerMap, String proxyHost, final int proxyPort,
                                      int connectTimeout, int readTimeout, byte[] reqContent) {
        HttpsURLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            URL serverUrl = new URL(url);
            if (!isEmpty(proxyHost) && proxyPort != 0) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
                urlConnection = (HttpsURLConnection) (serverUrl.openConnection(proxy));
            } else {
                urlConnection = (HttpsURLConnection) (serverUrl.openConnection());
            }
            if (url.startsWith("https")) {
                SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, new TrustManager[]{new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }
                }}, new SecureRandom());
                urlConnection.setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });
            }
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setRequestMethod(method);
            urlConnection.setConnectTimeout(connectTimeout);
            urlConnection.setReadTimeout(readTimeout);
            if (headerMap != null && headerMap.size() > 0) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            //封装的请求头 urlConnection.getRequestProperties();
            if (reqContent != null && reqContent.length > 0) {
                //需要写数据到请求体中 因为默认是GET请求,所以
                urlConnection.setDoOutput(true);
                OutputStream outputStream = urlConnection.getOutputStream();
                outputStream.write(reqContent);
                outputStream.flush();
                outputStream.close();
            }
            //getInputStream()会隐式的调用urlConnection.connect() 并将请求体上传至服务器
            inputStream = urlConnection.getInputStream();
            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                //返回的请求头 urlConnection.getHeaderFields();
                return IOUtil.readInputStream(inputStream);
            }
        } catch (IOException | NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        } finally {
            IOUtil.close(inputStream);
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
        return null;
    }

    /**
     * 将K-V的参数转为k&v的形式
     *
     * @param paramMap
     * @return
     */
    public static String joinParas(Map<String, String> paramMap) {
        if (paramMap == null || paramMap.size() == 0) {
            return "";
        }
        StringBuilder paras = new StringBuilder();
        Iterator<Map.Entry<String, String>> ite = paramMap.entrySet().iterator();
        while (ite.hasNext()) {
            Map.Entry<String, String> entry = ite.next();
            paras.append(entry.getKey()).append("=").append(utf8Encode(entry.getValue()));
            if (ite.hasNext()) {
                paras.append("&");
            }
        }
        return paras.toString();
    }

    /**
     * 将K-V的参数转为k&v的形式并进行encode编码
     *
     * @param paramMap
     * @return
     */
    public static String joinEncodeParas(Map<String, String> paramMap) {
        if (paramMap == null || paramMap.size() == 0) {
            return "";
        }
        StringBuilder paras = new StringBuilder();
        Iterator<Map.Entry<String, String>> ite = paramMap.entrySet().iterator();
        while (ite.hasNext()) {
            Map.Entry<String, String> entry = ite.next();
            paras.append(entry.getKey()).append("=").append(entry.getValue());
            if (ite.hasNext()) {
                paras.append("&");
            }
        }
        return paras.toString();
    }

    /**
     * 是否为空的判断
     *
     * @param str
     * @return
     */
    private static boolean isEmpty(CharSequence str) {
        return (null == str || str.length() == 0);
    }

    /**
     * 将字符串进行UTF-8编码
     *
     * @param str
     * @return
     */
    private static String utf8Encode(String str) {
        if (!isEmpty(str) && str.getBytes().length != str.length()) {
            try {
                return URLEncoder.encode(str, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return str;
            }
        }
        return str;
    }

}

标签:urlConnection,return,请求,url,param,headerMap,封装,Android,HttpURLConnection
来源: https://www.cnblogs.com/alasola/p/15712645.html