栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

java http请求工具类(https)

Java 更新时间:发布时间: 百科书网 趣学号
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.activation.MimetypesFileTypeMap;
import javax.net.ssl.*;
import java.security.cert.Certificate;



public class HttpUtil {


    public static final String DEFAULT_CHARSET = "UTF-8";
    public static final String METHOD_POST = "POST";
    public static final String METHOD_GET = "GET";
    public static final int BUFFER_SIZE = 8192; // 8K
    public static final int CONNECT_TIMEOUT = 3000; // 3s
    public static final int READ_TIMEOUT = 60000; // 6s
    public static final int READ_FILE_TIMEOUT = 3600000; // 3600s

    public static final String KEY_X_REQUESTED_WITH = "X-Requested-With";
    public static final String KEY_USER_AGENT = "User-Agent";
    public static final String KEY_ACCEPT_ENCODING = "Accept-Encoding";
    public static final String KEY_CONTENT_TYPE = "Content-Type";
    public static final String KEY_ACCEPT_LANGUAGE = "Accept-Language";
    public static final String KEY_ConNECTION = "Connection";
    public static final String KEY_CACHE_ConTROL = "Cache-Control";
    public static final String KEY_ACCEPT = "Accept";
    public static final String KEY_CHARSERT = "Charsert";
    public static final String KEY_cookie = "cookie";

    // 定义数据分隔线
    private static String BOUNDARY = "---------------------------71a816d53b6o219";

    private HttpUtil() {
    }

    
    public static boolean isConnected(String url) {
        try {
            return isConnected(new URL(url), CONNECT_TIMEOUT);
        } catch (MalformedURLException e) {
            return false;
        }
    }

    
    public static boolean isConnected(String url, int timeout) {
        try {
            return isConnected(new URL(url), timeout);
        } catch (MalformedURLException e) {
            return false;
        }
    }

    
    public static boolean isConnected(URL url) {
        return isConnected(url, CONNECT_TIMEOUT);
    }

    
    public static boolean isConnected(URL url, int timeout) {
        HttpURLConnection httpConn = null;
        try {
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setConnectTimeout(timeout);
            httpConn.connect();
            int responseCode = httpConn.getResponseCode();
            return isSuccess(responseCode);
        } catch (Exception e) {
            return false;
        } finally {
            close(httpConn);
        }
    }

    
    public static HttpResult ajaxRequest(HttpParameter httpParameter) throws IOException {
        // Ajax 异步请求方式
        httpParameter.putDefaultProperty(KEY_X_REQUESTED_WITH, "XMLHttpRequest");
        return httpRequest(httpParameter);
    }

    
    public static HttpResult httpRequest(HttpParameter httpParameter) throws IOException {
        HttpURLConnection httpConn = null;
        try {
            httpConn = getHttpConn(httpParameter);
            return getResponseAsString(httpConn);
        } finally {
            close(httpConn);
        }
    }

    
    public static File ajaxDownload(HttpParameter httpParameter, File file) throws IOException {
        // Ajax 异步请求方式
        httpParameter.putDefaultProperty(KEY_X_REQUESTED_WITH, "XMLHttpRequest");
        return httpDownload(httpParameter, file);
    }

    
    public static File httpDownload(HttpParameter httpParameter, File file) throws IOException {
        HttpURLConnection httpConn = null;
        try {
            httpConn = getHttpConn(httpParameter);
            return getResponseAsFile(httpConn, file);
        } finally {
            close(httpConn);
        }
    }

    
    public static HttpResult ajaxUpload(HttpParameter httpParameter, List fileList) throws IOException {
        // Ajax 异步请求方式
        httpParameter.putDefaultProperty(KEY_X_REQUESTED_WITH, "XMLHttpRequest");
        return httpUpload(httpParameter, fileList);
    }

    
    public static HttpResult ajaxUpload(HttpParameter httpParameter, Map fileMap) throws IOException {
        // Ajax 异步请求方式
        httpParameter.putDefaultProperty(KEY_X_REQUESTED_WITH, "XMLHttpRequest");
        return httpUpload(httpParameter, fileMap);
    }

    
    public static HttpResult httpUpload(HttpParameter httpParameter, List fileList) throws IOException {
        Map fileMap = new HashMap();
        for (File file : fileList) {
            fileMap.put(file.getName(), file);
        }
        return httpUpload(httpParameter, fileMap);
    }

    
    public static HttpResult httpUpload(HttpParameter httpParameter, Map fileMap) throws IOException {
        String url = httpParameter.getUrl();
        Map params = httpParameter.getParams();
        Map property = httpParameter.getProperty();
        int connectTimeout = httpParameter.getConnectTimeout();
        int readTimeout = httpParameter.getReadTimeout();

        HttpURLConnection httpConn = null;
        OutputStream out = null;
        try {
            String contentType = "multipart/form-data; boundary=" + BOUNDARY;
            property.put(KEY_CONTENT_TYPE, contentType);
            httpConn = openHttpConn(new URL(url), connectTimeout, readTimeout, METHOD_POST, property);

            out = new DataOutputStream(httpConn.getOutputStream());
            appendContent(params, out);
            appendFile(fileMap, out);
            byte[] endData = ("rn--" + BOUNDARY + "--rn").getBytes();
            out.write(endData);
            out.flush();
            return getResponseAsString(httpConn);
        } finally {
            close(out);
            close(httpConn);
        }
    }

    
    public static HttpURLConnection getHttpConn(HttpParameter httpParameter) throws IOException {
        String charset = httpParameter.getCharset();
        if (StringUtil.isEmpty(charset)) {
            charset = DEFAULT_CHARSET;
        }
        String url = httpParameter.getUrl();
        Map params = httpParameter.getParams();
        params = buildParams(url, params);
        String content = getParamsContext(params, charset);
        String method = httpParameter.getMethod();
        if (METHOD_POST.equalsIgnoreCase(method)) {
            url = tranferUrl(url);
        }
        Map property = httpParameter.getProperty();
        // 设置请求的 HTTP内容类型
        String contentType = "application/x-www-form-urlencoded;charset=" + charset;
        httpParameter.putDefaultProperty(KEY_CONTENT_TYPE, contentType);
        httpParameter.putDefaultProperty(KEY_ACCEPT, "*
    private static HttpURLConnection openHttpConn(URL url, int connectTimeout, int readTimeout, String method,
                                                  Map property) throws IOException {

        HttpURLConnection httpConn;
        if (url.toString().toLowerCase().startsWith("https")) {
            try {
                // 创建SSLContext对象,并使用我们指定的信任管理器初始化
                TrustManager[] tm = { new X509TrustManagerNone() };
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, tm, null);
                SSLSocketFactory ssf = sslContext.getSocketFactory();
                httpConn = (HttpsURLConnection) url.openConnection();
                ((HttpsURLConnection) httpConn).setSSLSocketFactory(ssf);
                ((HttpsURLConnection) httpConn).setHostnameVerifier(new AllowAllHostnameVerifier());
            } catch(Exception e) {
                throw new IOException(e);
            }
        } else {
            httpConn = (HttpURLConnection) url.openConnection();
        }
        if (StringUtil.isEmpty(method)) {
            method = METHOD_POST;
        }
        // 设定请求的方法,默认是GET
        httpConn.setRequestMethod(method);
        if ("POST".equalsIgnoreCase(method)) {
            // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在
            // http正文内,因此需要设为true, 默认情况下是false;
            httpConn.setDoOutput(true);
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            httpConn.setDoInput(true);
            // Post 请求不能使用缓存
            httpConn.setUseCaches(false);
        }

        if (connectTimeout != -1) {
            // 设置连接超时时间
            httpConn.setConnectTimeout(connectTimeout > 0 ? connectTimeout : CONNECT_TIMEOUT);
        }
        if (readTimeout != -1) {
            // 设置读取超时时间
            httpConn.setReadTimeout(readTimeout > 0 ? readTimeout : READ_TIMEOUT);
        }

        for (Entry entry : property.entrySet()) {
            httpConn.setRequestProperty(entry.getKey(), entry.getValue());
        }
        return httpConn;
    }

    
    private static void appendContent(Map textMap, OutputStream out) throws IOException {
        if (textMap == null) {
            return;
        }
        StringBuffer contentBuffer = new StringBuffer();
        for (Entry entry : textMap.entrySet()) {
            String inputName = entry.getKey();
            String inputValue = entry.getValue();
            if (inputValue == null) {
                continue;
            }
            contentBuffer.append("rn").append("--").append(BOUNDARY).append("rn");
            contentBuffer.append("Content-Disposition: form-data; name="" + inputName + ""rnrn");
            contentBuffer.append(inputValue);
        }
        out.write(contentBuffer.toString().getBytes());
    }

    
    private static void appendFile(Map fileMap, OutputStream out) throws IOException {
        if (fileMap == null) {
            return;
        }
        for (Entry entry : fileMap.entrySet()) {
            String inputName = entry.getKey();
            File file = entry.getValue();
            if (file == null) {
                continue;
            }
            upFile(inputName, file, out);
        }
    }

    private static void upFile(String inputName, File file, OutputStream out) throws IOException {
        if (file.isDirectory()) {
            File[] listFiles = file.listFiles();
            if (listFiles != null) {
                for (int i = 0; i < listFiles.length; i++) {
                    upFile(inputName + "_" + i, listFiles[i], out);
                }
            }
        } else {
            String filename = file.getName();
            String contentType = new MimetypesFileTypeMap().getContentType(file);

            if (contentType == null || contentType.equals("")) {
                contentType = "application/octet-stream";
            }

            StringBuffer strBuf = new StringBuffer();
            strBuf.append("rn").append("--").append(BOUNDARY).append("rn");
            strBuf.append("Content-Disposition: form-data;name="" + inputName + ""; filename="" + filename + ""rn");
            strBuf.append("Content-Type:" + contentType + "rnrn");

            out.write(strBuf.toString().getBytes());

            int length = 0;
            byte[] buffer = new byte[1024];
            DataInputStream in = null;
            try {
                in = new DataInputStream(new FileInputStream(file));
                while ((length = in.read(buffer)) != -1) {
                    out.write(buffer, 0, length);
                }
            } finally {
                close(in);
            }
        }
    }

    
    private static boolean isSuccess(int responseCode) {
        return (responseCode >= 200 && responseCode < 300);// || responseCode == 404;
    }

    
    private static String tranferUrl(String url) throws MalformedURLException, UnsupportedEncodingException {
        if (url != null) {
            URL _url = new URL(url);
            String path = _url.getPath();
            String DOT_RE = "/\./";
            String DOUBLE_DOT_RE = "/[^/]+/\.\./";

            path = path.replaceAll(DOT_RE, "/");
            Pattern p = Pattern.compile(DOUBLE_DOT_RE);
            Matcher m = p.matcher(path);
            while (m.find()) {
                String a = path.substring(m.start(), m.end());
                path = path.replaceFirst(a, "/");
                m = p.matcher(path);
            }
            path = path.replaceAll("/\.\./", "/");
            url = _url.getProtocol() + "://" + _url.getHost() + (_url.getPort() > 0 ? ":" + _url.getPort() : "") + path;
        }
        // 加入对url中包括非URI格式的处理
        if (url != null && url.indexOf("&") > -1) {
            int idx = -1;
            String prefiex = null;
            StringBuilder sb = new StringBuilder();
            while ((idx = url.indexOf("&")) > -1) {
                if (prefiex == null) {
                    prefiex = url.substring(0, idx);
                }
                url = url.substring(idx + 1, url.length());
                int split = url.indexOf("=");
                String key = url.substring(0, split);
                int last = url.indexOf("&");
                String value;
                if (last > -1) {
                    value = url.substring(split + 1, last);
                } else {
                    value = url.substring(split + 1, url.length());
                }
                value = URLEncoder.encode(value, "UTF-8");
                sb.append("&" + key + "=" + value);
            }
            url = prefiex + sb.toString();
        }
        int mark = url.indexOf("?");
        // 已经包含参数
        if (mark > -1) {
            url = url.substring(0, mark);
        }
        return url;
    }

    private static Map buildParams(String url, Map params) {
        int mark = url.indexOf("?");
        // 已经包含参数
        if (mark > -1) {
            String _params = url.substring(mark + 1, url.length());
            url = url.substring(0, mark);
            String[] paramArray = _params.split("&");
            if (params == null) {
                params = new HashMap();
            }
            for (int i = 0; i < paramArray.length; i++) {
                String string = paramArray[i];
                int index = string.indexOf("=");
                if (index > 0) {
                    String key = string.substring(0, index);
                    String value = string.substring(index + 1, string.length());
                    params.put(key, value);
                }
            }
        }
        return params;
    }

    private static String getParamsContext(Map params, String charset)
            throws UnsupportedEncodingException {
        if ((params == null) || (params.isEmpty())) {
            return null;
        }

        StringBuilder query = new StringBuilder();
        Set> entries = params.entrySet();
        boolean hasParam = false;
        for (Map.Entry entry : entries) {
            String name = entry.getKey();
            String value = entry.getValue();
            if (hasParam) {
                query.append("&");
            } else {
                hasParam = true;
            }

            if (!isEmpty(name) && !isEmpty(value)) {
                query.append(name).append("=").append(URLEncoder.encode(value, charset));
            } else if (!isEmpty(name)) {
                query.append(name).append("=");
            }
        }
        return query.toString();
    }

    
    private static HttpResult getResponseAsString(HttpURLConnection httpConn) throws IOException {
        String charset = getResponseCharset(httpConn.getContentType());
        InputStream errorStream = httpConn.getErrorStream();
        HttpResult httpResult = new HttpResult();
        httpResult.setResponseCode(httpConn.getResponseCode());
        if (errorStream == null) {
            httpResult.setSuccess(true);
            httpResult.setMessage(getStreamAsString(httpConn.getInputStream(), charset));
        } else {
            httpResult.setSuccess(false);
            httpResult.setMessage(getStreamAsString(errorStream, charset));
        }
        return httpResult;
    }

    
    private static File getResponseAsFile(HttpURLConnection httpConn, File file) throws IOException {
        String charset = getResponseCharset(httpConn.getContentType());
        InputStream errorStream = httpConn.getErrorStream();
        if (errorStream != null) {
            String streamAsString = getStreamAsString(errorStream, charset);
            throw new RuntimeException(streamAsString);
        }
        writeFileByInputStream(file, httpConn.getInputStream());
        return file;
    }

    
    private static void writeFileByInputStream(File file, InputStream inputStream) throws IOException {
        OutputStream out = null;
        if (!file.getParentFile().exists()) { // 如果目录不存在则创建目录
            file.getParentFile().mkdirs();
        }
        try {
            out = new FileOutputStream(file);
            byte[] buffer = new byte[BUFFER_SIZE];
            int read;
            while ((read = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, read);
                out.flush();
            }
        } finally {
            close(inputStream);
            close(out);
        }
    }

    
    private static String getStreamAsString(InputStream stream, String charset) throws IOException {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
            StringWriter writer = new StringWriter();
            char[] buffer = new char[BUFFER_SIZE];
            int length = 0;
            while ((length = reader.read(buffer)) > 0) {
                writer.write(buffer, 0, length);
            }
            return writer.toString();
        } finally {
            close(stream);
        }
    }

    
    private static String getResponseCharset(String contentType) {
        String charset = DEFAULT_CHARSET;
        if (!isEmpty(contentType)) {
            String[] params = contentType.split(";");
            for (String param : params) {
                param = param.trim();
                if (param.startsWith("charset")) {
                    String[] pair = param.split("=", 2);
                    if ((pair.length != 2) || (isEmpty(pair[1])))
                        break;
                    charset = pair[1].trim();
                    break;
                }
            }
        }
        return charset;
    }

    
    private static boolean isEmpty(String msg) {
        return msg == null || msg.trim().length() == 0;
    }

    
    public static void close(Closeable object) {
        try {
            if (object != null) {
                object.close();
            }
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
        }
    }

    
    public static void close(HttpURLConnection conn) {
        try {
            if (conn != null) {
                close(conn.getInputStream());
                close(conn.getErrorStream());
                conn.disconnect();
            }
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
        }
    }

    
    public static class HttpResult implements Serializable {

        private static final long serialVersionUID = 1L;

        private boolean success;
        private String message;
        private int responseCode;

        public boolean isSuccess() {
            return success;
        }

        public void setSuccess(boolean success) {
            this.success = success;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public int getResponseCode() {
            return responseCode;
        }

        public void setResponseCode(int responseCode) {
            this.responseCode = responseCode;
        }

    }

    
    public static class HttpParameter implements Serializable {

        private static final long serialVersionUID = 1L;

        private String url;
        private int connectTimeout;
        private int readTimeout;
        private String method;
        private Map params;
        private String charset;
        private Map property;

        public HttpParameter(String url) {
            this(url, CONNECT_TIMEOUT, READ_TIMEOUT, METHOD_POST, null, DEFAULT_CHARSET, new HashMap());
        }

        public HttpParameter(String url, int connectTimeout, int readTimeout) {
            this(url, connectTimeout, readTimeout, METHOD_POST, null, DEFAULT_CHARSET, new HashMap());
        }

        public HttpParameter(String url, int connectTimeout, int readTimeout, String method) {
            this(url, connectTimeout, readTimeout, method, null, DEFAULT_CHARSET, new HashMap());
        }

        public HttpParameter(String url, int connectTimeout, int readTimeout, String method, Map params) {
            this(url, connectTimeout, readTimeout, method, params, DEFAULT_CHARSET, new HashMap());
        }

        public HttpParameter(String url, int connectTimeout, int readTimeout, String method, Map params,
                             String charset) {
            this(url, connectTimeout, readTimeout, method, params, charset, new HashMap());
        }

        public HttpParameter(String url, int connectTimeout, int readTimeout, String method, Map params,
                             String charset, Map property) {
            super();
            this.url = url;
            this.connectTimeout = connectTimeout;
            this.readTimeout = readTimeout;
            this.method = method;
            this.params = params;
            this.charset = charset;
            this.property = property;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public int getConnectTimeout() {
            return connectTimeout;
        }

        public void setConnectTimeout(int connectTimeout) {
            this.connectTimeout = connectTimeout;
        }

        public int getReadTimeout() {
            return readTimeout;
        }

        public void setReadTimeout(int readTimeout) {
            this.readTimeout = readTimeout;
        }

        public String getMethod() {
            return method;
        }

        public void setMethod(String method) {
            this.method = method;
        }

        public Map getParams() {
            return params;
        }

        public void setParams(Map params) {
            this.params = params;
        }

        public String getCharset() {
            return charset;
        }

        public void setCharset(String charset) {
            this.charset = charset;
        }

        public Map getProperty() {
            if (property == null) {
                property = new HashMap();
            }
            return property;
        }

        public void setProperty(Map property) {
            this.property = property;
        }

        public void putDefaultProperty(String key, String value) {
            Map property = getProperty();
            String result = property.get(key);
            if (result == null) {
                property.put(key, value);
            }
        }

    }

    public static class X509TrustManagerNone implements X509TrustManager {


        X509TrustManager sunJSSEX509TrustManager;

        public X509TrustManagerNone() throws Exception {

        }


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

        }

        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    public static class AllowAllHostnameVerifier implements HostnameVerifier {
        public boolean verify(String host, SSLSession session) {
            try {
                Certificate[] certs = session.getPeerCertificates();

                return ((certs != null) && (certs[0] instanceof X509Certificate));
            } catch (SSLException e) {
            }
            return false;
        }
    }

}

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/275111.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号