package xx.utils;
import java.io.BufferedReader;
import java.io.IOException;

import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import java.nio.charset.StandardCharsets;

import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import javax.net.ssl.SSLSocketFactory;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.ekyb.common.authrity.action.AuUserAction;

import net.sf.json.JSONObject;

import javax.net.ssl.SSLContext;

import javax.net.ssl.TrustManager;

import java.io.ByteArrayOutputStream;

import java.io.DataOutputStream;

import java.io.InputStream;

import java.security.KeyManagementException;

import java.security.NoSuchAlgorithmException;

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;

import javax.net.ssl.SSLSession;

import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;

@Service

public class HttpUtil {
    private static Logger LOG = Logger.getLogger(HttpUtil.class);

    /**
     * 向指定 URL 发送POST方法的请求
     * https
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */

    public static String sendHttpsPost(String url, String param, Map<String,String> headerMap) {

        PrintWriter out = null;

        BufferedReader in = null;

        String result = "";

        try {



            // 创建SSLContext对象,并使用我们指定的信任管理器初始化

            TrustManager[] tm = { new MyX509TrustManager() };

            SSLContext sslContext = SSLContext.getInstance("SSL");

            sslContext.init(null, tm, new java.security.SecureRandom());



            // 从上述SSLContext对象中得到SSLSocketFactory对象

            SSLSocketFactory ssf = sslContext.getSocketFactory();



            // 打开和URL之间的连接

            URL realUrl = new URL(url);

            HttpsURLConnection conn = (HttpsURLConnection) realUrl.openConnection();

            conn.setSSLSocketFactory(ssf);



            // 设置通用的请求属性

            conn.setRequestProperty("accept", "*/*");

            conn.setRequestProperty("Connection", "Keep-Alive");

            conn.setRequestProperty("Content-Type", "application/json");

            conn.setRequestProperty("user-agent",

                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            if(headerMap != null){

                headerMap.forEach((key,value)->{

                    conn.setRequestProperty(key, value);

                });

            }



            // 发送POST请求必须设置如下两行

            conn.setDoOutput(true);

            conn.setDoInput(true);

            // 获取URLConnection对象对应的输出流

            out = new PrintWriter(conn.getOutputStream());

            // 发送请求参数



            out.print(param);

            // flush输出流的缓冲

            out.flush();

            // 定义BufferedReader输入流来读取URL的响应

            in = new BufferedReader(

                    new InputStreamReader(conn.getInputStream()));

            String line;

            while ((line = in.readLine()) != null) {

                result += line;

            }

            System.out.println("-----result-----"+result);

        } catch (Exception e) {

            System.out.println("发送 POST 请求出现异常!"+e);

            e.printStackTrace();

        }

        //使用finally块来关闭输出流、输入流

        finally{

            try{

                if(out!=null){

                    out.close();

                }

                if(in!=null){

                    in.close();

                }

            }

            catch(IOException ex){

                ex.printStackTrace();

            }

        }

        return result;

    }





    /**

     * 发送POST请求

     *

     */

    public static String sendHttpPost(String uri, String param, Map<String,String> headerMap) throws IOException {

        CloseableHttpClient httpClient = HttpClients.createDefault();

        //设置超时时间

        RequestConfig requestConfig = RequestConfig.custom()

                .setConnectTimeout(3000).setConnectionRequestTimeout(2000)

                .setSocketTimeout(3000).build();

        HttpPost post = new HttpPost(uri);

        post.setConfig(requestConfig);

        post.setHeader("Content-Type", "application/json");

        if(headerMap != null){

            headerMap.forEach((key,value) -> {

                post.setHeader(key, value);

            });

        }


//        StringEntity entity = new StringEntity(param, StandardCharsets.UTF_8);
        StringEntity entity = new StringEntity(param);
        post.setEntity(entity);
        HttpResponse response = httpClient.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            // throw new RuntimeException("http请求异常" + statusCode);
        }
        return EntityUtils.toString(response.getEntity(), "UTF-8");

    }



    private static class TrustAnyTrustManager implements X509TrustManager {



        public void checkClientTrusted(X509Certificate[] chain, String authType)

                throws CertificateException {

        }



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

                throws CertificateException {

        }



        public X509Certificate[] getAcceptedIssuers() {

            return new X509Certificate[] {};

        }

    }



    private static class TrustAnyHostnameVerifier implements HostnameVerifier {

        public boolean verify(String hostname, SSLSession session) {

            return true;

        }

    }



    /**

     * post方式请求服务器(https协议)

     *

     * @param url

     *            请求地址

     * @param content

     *            参数

     * @param charset

     *            编码

     * @return

     * @throws NoSuchAlgorithmException

     * @throws KeyManagementException

     * @throws IOException

     */

    public static String sendHttpsPostx(String url, String jsonParamStr, Map<String,String> headerMap)

            throws NoSuchAlgorithmException, KeyManagementException,

            IOException {

        System.setProperty("jsse.enableSNIExtension", "false");

        SSLContext sc = SSLContext.getInstance("SSL");

        sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },

                new java.security.SecureRandom());



        URL console = new URL(url);

        HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();

        conn.setSSLSocketFactory(sc.getSocketFactory());

        conn.setHostnameVerifier(new TrustAnyHostnameVerifier());



        conn.setConnectTimeout(30000);

        conn.setReadTimeout(30000);

        // 设置通用的请求属性

        conn.setRequestProperty("accept", "*/*");

        conn.setRequestProperty("Connection", "Keep-Alive");

        conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

        conn.setRequestProperty("user-agent",

                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

        if(headerMap != null){

            headerMap.forEach((key,value)->{

                conn.setRequestProperty(key, value);

            });

        }



        conn.setDoOutput(true);

        conn.connect();

        DataOutputStream out = new DataOutputStream(conn.getOutputStream());

        out.write(jsonParamStr.getBytes("UTF-8"));

        // 刷新、关闭

        out.flush();

        out.close();

        InputStream is = conn.getInputStream();

        if (is != null) {

            ByteArrayOutputStream outStream = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];

            int len = 0;

            while ((len = is.read(buffer)) != -1) {

                outStream.write(buffer, 0, len);

            }

            is.close();

            return new String(outStream.toByteArray()) ;

        }

        return null;

    }



public static String doGet(String httpurl) {
        
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式:get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间:15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间:60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接,获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封装输入流is,并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
 
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
 
            connection.disconnect();// 关闭远程连接
        }
 
        return result;
    }
    
/*
 * 新的方式http方式
 * */
    public static String doPost(String httpUrl, String param) {
 
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间:15000毫秒
            connection.setConnectTimeout(150000);
            // 设置读取主机服务器返回数据超时时间:60000毫秒
            connection.setReadTimeout(600000);
 
            // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
            connection.setDoOutput(true);
            // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
            connection.setRequestProperty("Authorization",
                    "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            os.write(param.getBytes());
            // 通过连接对象获取一个输入流,向远程读取
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
 
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
//                    sbf.append("\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }
    
    /**
     * 发送post请求
     * @param URL
     * @param json
     *
     * @return
     */
    public static String sendPost(String URL,JSONObject json, Map<String,String> headerMap) {
        LOG.info("sendPost(url:"+ URL +" ,paramsJson:"+json.toString()+" )");
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        post.setHeader("Content-Type", "application/json");
        if(headerMap != null){
            headerMap.forEach((key,value) -> {
                post.setHeader(key, value);
            });
        }
//        post.addHeader("Authorization", "Basic YWRtaW46");
        String result;
        try {
            StringEntity s = new StringEntity(json.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
            post.setEntity(s);
            // 发送请求
            HttpResponse httpResponse = client.execute(post);
            // 获取响应输入流
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null){
//                strber.append(line + "");
//                strber.append(line + "\n");
                strber.append(line);
//                LOG.info("line---------\n"+line);
            }
                
            inStream.close();
            result = strber.toString();
            LOG.info("result---------\n"+result);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                LOG.info("请求服务器成功,做相应处理");
            } else {
                LOG.info("请求服务端失败");
            }
        } catch (Throwable e) {
//            logger.error("请求异常:"+e.getMessage());
            LOG.error("请求异常",e);
//            throw new RuntimeException(e);
            return null;
        }
        return result;
    }
    
    /** 
     * 获取用户真实IP地址,不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址, 
     * 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值,究竟哪个才是真正的用户端的真实IP呢? 
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。 
     *  
     * 如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130, 
     * 192.168.1.100 
     *  
     * 用户真实IP为: 192.168.1.110 
     *  
     * @param request 
     * @return 
     */  
    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;  
    }  

}

 

posted on 2022-05-27 12:12  Dawn.Break  阅读(88)  评论(0)    收藏  举报