All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.soento.core.util.HttpUtil Maven / Gradle / Ivy

package com.soento.core.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * http 工具类
 *
 * @author soento
 */
@Slf4j
public final class HttpUtil {
    private final static String UNKNOWN = "unknown";
    private final static String XML_HTTP_REQUEST = "XMLHttpRequest";

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 判断是否为AJAX请求
     *
     * @return true:是;false:否
     */
    public static boolean isAjax(HttpServletRequest request) {
        String pattern = ".*application/json.*";

        String accept = request.getHeader("Accept");
        if (accept != null && Pattern.compile(pattern).matcher(accept).matches()) {
            return true;
        }
        String contentType = request.getHeader("Content-Type");
        if (contentType != null && Pattern.compile(pattern).matcher(contentType).matches()) {
            return true;
        }
        String requested = request.getHeader("x-requested-with");
        if (XML_HTTP_REQUEST.equals(requested)) {
            return true;
        }
        return false;
    }

    private static CloseableHttpClient getHttpClient() {
        try {
            return SpringUtil.getBean(CloseableHttpClient.class);
        } catch (Throwable e) {
            return HttpClientBuilder.create().build();
        }
    }

    private static RequestConfig getConfig() {
        try {
            return SpringUtil.getBean(RequestConfig.class);
        } catch (Throwable e) {
            return RequestConfig.custom().build();
        }
    }

    public static String get(String url) {
        try {
            log.info("↓↓↓↓↓↓ GET ↓↓↓↓↓↓");
            log.info("URL : {}", url);
            CloseableHttpClient httpClient = getHttpClient();
            RequestConfig config = getConfig();
            HttpGet get = new HttpGet(url);
            get.setConfig(config);
            CloseableHttpResponse response = httpClient.execute(get);
            String result = EntityUtils.toString(response.getEntity());
            log.info("RESULT : {}", result);
            log.info("↑↑↑↑↑↑ GET ↑↑↑↑↑↑");
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String convertParams(Map params) {
        StringBuilder result = new StringBuilder();
        for (String key : params.keySet()) {
            result.append(key);
            result.append("=");
            result.append(params.get(key));
            result.append("&");
        }
        return result.toString();
    }

    public static String post(String url, ContentType contentType, String params) {
        try {
            log.info("↓↓↓↓↓↓ POST ↓↓↓↓↓↓");
            log.info("URL : {}", url);
            log.info("PARAMS : {}", params);
            CloseableHttpClient httpClient = getHttpClient();
            RequestConfig config = getConfig();
            HttpPost post = new HttpPost(url);
            post.setConfig(config);
            ByteArrayEntity entity = new ByteArrayEntity(params.getBytes(StandardCharsets.UTF_8), contentType);
            post.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(post);
            String result = EntityUtils.toString(response.getEntity());
            log.info("RESULT : {}", result);
            log.info("↑↑↑↑↑↑ POST ↑↑↑↑↑↑");
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String post(String url, String params) {
        return post(url, ContentType.create("application/x-www-form-urlencoded", StandardCharsets.UTF_8), params);
    }

    public static String postJson(String url, String params) {
        return post(url, ContentType.create("application/json", StandardCharsets.UTF_8), params);
    }


    public static String upload(String url, File[] files, String params) {
        try {
            log.info("↓↓↓↓↓↓ UPLOAD ↓↓↓↓↓↓");
            log.info("URL : {}", url);
            CloseableHttpClient httpClient = getHttpClient();
            RequestConfig config = getConfig();
            HttpPost post = new HttpPost(url);
            post.setConfig(config);
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            if (files != null && files.length > 0) {
                for (int i = 0; i < files.length; i++) {
                    log.info("File Path : {}", files[i].getPath());
                    entityBuilder.addBinaryBody("file" + i, files[i],
                            ContentType.create("application/octet-stream", StandardCharsets.UTF_8),
                            files[i].getName());
                }
            }
            if (StringUtil.isNotBlank(params)) {
                String[] paramKV = params.split("&");
                for (String kv : paramKV) {
                    String[] tmp = kv.split("=");
                    if (tmp.length == 2) {
                        String k = tmp[0];
                        String v = tmp[1];
                        log.info("Param {} : {}", k, v);
                        entityBuilder.addTextBody(k, v, ContentType.create("text/plain", StandardCharsets.UTF_8));
                    }

                }
            }
            post.setEntity(entityBuilder.build());
            CloseableHttpResponse response = httpClient.execute(post);
            String result = EntityUtils.toString(response.getEntity());
            log.info("RESULT : {}", result);
            log.info("↑↑↑↑↑↑ UPLOAD ↑↑↑↑↑↑");
            return result;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static File download(String url, String path) {
        File file;
        BufferedInputStream in = null;
        OutputStream out = null;
        try {
            log.info("↓↓↓↓↓↓ DOWNLOAD ↓↓↓↓↓↓");
            log.info("URL : {}", url);
            CloseableHttpClient httpClient = getHttpClient();
            RequestConfig config = getConfig();
            HttpGet get = new HttpGet(url);
            get.setConfig(config);
            CloseableHttpResponse response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            in = new BufferedInputStream(entity.getContent());
            file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            out = new FileOutputStream(file);
            int size = 0;
            byte[] buf = new byte[1024];
            while ((size = in.read(buf)) != -1) {
                out.write(buf, 0, size);
            }
            out.flush();
            log.info("FILE : {}", file.getPath());
            log.info("↑↑↑↑↑↑ DOWNLOAD ↑↑↑↑↑↑");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            StreamUtil.close(out);
            StreamUtil.close(in);
        }
        return file;

    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy