java:HttpUtil

import com.alibaba.fastjson.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.utils.URIBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtil {

    private HttpUtil(){}

    private static Log logger = LogFactory.getLog(HttpUtil.class);


    /**
     * 發送HTTP_GET請求
     *  該方法會自動關閉連接,釋放資源
     * @param reqURL    請求地址(含參數)
     * @param decodeCharset 解碼字符集,解析響應數據時用之,其爲null時默認採用UTF-8解碼
     * @return 遠程主機響應正文
     */
    public static String sendGetRequest(String reqURL, String decodeCharset){
        long responseLength = 0;       //響應長度
        String responseContent = null; //響應內容
        HttpClient httpClient = new DefaultHttpClient(); //創建默認的httpClient實例
        HttpGet httpGet = new HttpGet(reqURL);           //創建org.apache.http.client.methods.HttpGet
        try{
            HttpResponse response = httpClient.execute(httpGet); //執行GET請求
            HttpEntity entity = response.getEntity();            //獲取響應實體
            if(null != entity){
                responseLength = entity.getContentLength();
                responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
                EntityUtils.consume(entity); //Consume response content
            }
            System.out.println("請求地址: " + httpGet.getURI());
            System.out.println("響應狀態: " + response.getStatusLine());
            System.out.println("響應長度: " + responseLength);
            System.out.println("響應內容: " + responseContent);
        }catch(ClientProtocolException e){
            logger.debug("該異常通常是協議錯誤導致,比如構造HttpGet對象時傳入的協議不對(將'http'寫成'htp')或者服務器端返回的內容不符合HTTP協議要求等,堆棧信息如下", e);
        }catch(ParseException e){
            logger.debug(e.getMessage(), e);
        }catch(IOException e){
            logger.debug("該異常通常是網絡原因引起的,如HTTP服務器未啓動等,堆棧信息如下", e);
        }finally{
            httpClient.getConnectionManager().shutdown(); //關閉連接,釋放資源
        }
        return responseContent;
    }


    /**
     * 發送HTTP_POST請求
     * 該方法爲sendPostRequest(String,String,boolean,String,String) 的簡化方法該方法在對請求數據的編碼和響應數據的解碼時,所採用的字符集均爲UTF-8
     * 當 isEncoder=true時,其會自動對sendData中的[中文][|][ ]等特殊字符進行URLEncoder.encode(string,"UTF-8")
     * @param isEncoder 用於指明請求數據是否需要UTF-8編碼,true爲需要
     */
    public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder){
        return sendPostRequest(reqURL, sendData, isEncoder, null, null);
    }


    /**
     * 發送HTTP_POST請求
     *  該方法會自動關閉連接,釋放資源
     *  當isEncoder=true時,其會自動對sendData中的[中文][|][ ]等特殊字符進行URLEncoder.encode(string,encodeCharset)
     * @param reqURL        請求地址
     * @param sendData      請求參數,若有多個參數則應拼接成param11=value11&22=value22&33=value33的形式後,傳入該參數中
     * @param isEncoder     請求數據是否需要encodeCharset編碼,true爲需要
     * @param encodeCharset 編碼字符集,編碼請求數據時用之,其爲null時默認採用UTF-8解碼
     * @param decodeCharset 解碼字符集,解析響應數據時用之,其爲null時默認採用UTF-8解碼
     * @return 遠程主機響應正文
     */
    public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder, String encodeCharset, String decodeCharset){
        String responseContent = null;
        HttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost(reqURL);
        //httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8");
        httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
        try{
            if(isEncoder){
                List formParams = new ArrayList();
                for(String str : sendData.split("&")){
                    formParams.add(new BasicNameValuePair(str.substring(0,str.indexOf("=")), str.substring(str.indexOf("=")+1)));
                }
                httpPost.setEntity(new StringEntity(URLEncodedUtils.format(formParams, encodeCharset==null ? "UTF-8" : encodeCharset)));
            }else{
                httpPost.setEntity(new StringEntity(sendData));
            }

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
                EntityUtils.consume(entity);
            }
        }catch(Exception e){
            logger.debug("與[" + reqURL + "]通信過程中發生異常,堆棧信息如下", e);
        }finally{
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }


    /**
     * 發送HTTP_POST請求
     * 該方法會自動關閉連接,釋放資源
     * 該方法會自動對 params中的[中文][|][ ]等特殊字符進行URLEncoder.encode(string,encodeCharset)
     * @param reqURL        請求地址
     * @param params        請求參數
     * @param encodeCharset 編碼字符集,編碼請求數據時用之,其爲null時默認採用UTF-8解碼
     * @param decodeCharset 解碼字符集,解析響應數據時用之,其爲null時默認採用UTF-8解碼
     * @return 遠程主機響應正文
     */
    public static String sendPostRequest(String reqURL, Map<Object,Map.Entry> params, String encodeCharset, String decodeCharset){
        String responseContent = null;
        HttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost(reqURL);
        List formParams = new ArrayList(); //創建參數隊列
        for(Map.Entry entry : params.entrySet()){
            formParams.add(new BasicNameValuePair((String)entry.getKey(), (String)entry.getValue()));
        }
        try{
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset==null ? "UTF-8" : encodeCharset));

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
                EntityUtils.consume(entity);
            }
        }catch(Exception e){
            logger.debug("與[" + reqURL + "]通信過程中發生異常,堆棧信息如下", e);
        }finally{
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }


    /**
     * 發送HTTPS_POST請求
     * 該方法爲sendPostSSLRequest(String,Map,String,String)方法的簡化方法
     * 該方法在對請求數據的編碼和響應數據的解碼時,所採用的字符集均爲UTF-8
     * 該方法會自動對params中的[中文][|][ ]等特殊字符進行URLEncoder.encode(string,"UTF-8")
     */
    public static String sendPostSSLRequest(String reqURL, Map params){
        return sendPostSSLRequest(reqURL, params, null, null);
    }


    /**
     * 發送HTTPS_POST請求
     * 該方法會自動關閉連接,釋放資源
     * 該方法會自動對 params中的[中文][|][ ]等特殊字符進行URLEncoder.encode(string,encodeCharset)
     * @param reqURL        請求地址
     * @param params        請求參數
     * @param encodeCharset 編碼字符集,編碼請求數據時用之,其爲null時默認採用UTF-8解碼
     * @param decodeCharset 解碼字符集,解析響應數據時用之,其爲null時默認採用UTF-8解碼
     * @return 遠程主機響應正文
     */
    public static String sendPostSSLRequest(String reqURL, Map<Object,Map.Entry> params, String encodeCharset, String decodeCharset){
        String responseContent = "";
        HttpClient httpClient = new DefaultHttpClient();
        X509TrustManager xtm = new X509TrustManager(){
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
            public X509Certificate[] getAcceptedIssuers() {return null;}
        };
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[]{xtm}, null);
            SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
            httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));

            HttpPost httpPost = new HttpPost(reqURL);
            List formParams = new ArrayList();
            for(Map.Entry entry : params.entrySet()){
                formParams.add(new BasicNameValuePair((String)entry.getKey(), (String)entry.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset==null ? "UTF-8" : encodeCharset));

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            logger.debug("與[" + reqURL + "]通信過程中發生異常,堆棧信息爲", e);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }


    /**
     * 發送HTTP_POST請求
     *  若發送的params 中含有中文,記得按照雙方約定的字符集將中文URLEncoder.encode(string,encodeCharset)
     * 本方法默認的連接超時時間爲30秒,默認的讀取超時時間爲30秒
     * @param reqURL 請求地址
     * @param params 發送到遠程主機的正文數據,其數據類型爲
    java.util.Map
     * @return 遠程主機響應正文`HTTP狀態碼,如
    "SUCCESS`200"

    若通信過程中發生異常則返回"Failed`HTTP狀態碼",如
    "Failed`500"
     */
    public static String sendPostRequestByJava(String reqURL, Map<Object,Map.Entry> params)throws Exception{
        StringBuilder sendData = new StringBuilder();
        for(Map.Entry entry : params.entrySet()){
            sendData.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        if(sendData.length() > 0){
            sendData.setLength(sendData.length() - 1); //刪除最後一個&符號
        }
        return sendPostRequestByJava(reqURL, sendData.toString());
    }

    /**
     * 發送HTTP_POST請求
     * 若發送的  params中含有中文,記得按照雙方約定的字符集將中文 URLEncoder.encode(string,encodeCharset)
     * 本方法默認的連接超時時間爲30秒,默認的讀取超時時間爲30秒
     * @param reqURL 請求地址
     * @param params 發送到遠程主機的正文數據,其數據類型爲
    java.util.Map
     * @return 遠程主機響應正文`HTTP狀態碼,如
    "SUCCESS`200"

    若通信過程中發生異常則返回"Failed`HTTP狀態碼",如
    "Failed`500"
     */
    public static String sendPostRequest(String reqURL, Map<String,Object> params)throws Exception{
        StringBuilder sendData = new StringBuilder();
        try {
            for(Map.Entry entry : params.entrySet()){
                sendData.append( URLEncoder.encode((String) entry.getKey(),"UTF-8"))
                        .append("=")
                        .append(URLEncoder.encode(null == entry.getValue()?"":entry.getValue().toString(),"UTF-8")).append("&");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw e ;
        }
        if(sendData.length() > 0){
            sendData.setLength(sendData.length() - 1); //刪除最後一個&符號
        }
        return sendPostRequestByJava(reqURL, sendData.toString());
    }


    /**
     * 發送HTTP_POST請求 若發送的sendData中含有中文,記得按照雙方約定的字符集將中文URLEncoder.encode(string,encodeCharset)
     * 本方法默認的連接超時時間爲30秒,默認的讀取超時時間爲30秒
     * @param reqURL   請求地址
     * @param sendData 發送到遠程主機的正文數據
     * @return 遠程主機響應正文`HTTP狀態碼,如
    "SUCCESS`200"

    若通信過程中發生異常則返回"Failed`HTTP狀態碼",如
    "Failed`500"
     */
    public static String sendPostRequestByJava(String reqURL, String sendData) throws Exception{
        HttpURLConnection httpURLConnection = null;
        OutputStream out = null; //寫
        InputStream in = null;   //讀
        int httpStatusCode = 0;  //遠程主機響應的HTTP狀態碼
        try{
            URL sendUrl = new URL(reqURL);
            httpURLConnection = (HttpURLConnection)sendUrl.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);        //指示應用程序要將數據寫入URL連接,其值默認爲false
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setConnectTimeout(30000); //30秒連接超時
            httpURLConnection.setReadTimeout(30000);    //30秒讀取超時

            out = httpURLConnection.getOutputStream();
            out.write(sendData.toString().getBytes());

            //清空緩衝區,發送數據
            out.flush();

            //獲取HTTP狀態碼
            httpStatusCode = httpURLConnection.getResponseCode();

            in = httpURLConnection.getInputStream();
            InputStreamReader reader = new InputStreamReader(in, "UTF-8");
            BufferedReader br = new BufferedReader(reader);
            String readLine = "";
            StringBuilder sb = new StringBuilder();
            while((readLine=br.readLine())!=null){
                sb.append(readLine);
            }
//            byte[] byteDatas = new byte[in.available()];
//            in.read(byteDatas);
            return sb.toString();
        }catch(Exception e){
            //logger.debug(e.getMessage());
            throw e ;
            //return "Failed`" + httpStatusCode;
        }finally{
            if(out != null){
                try{
                    out.close();
                }catch (Exception e){
                    logger.debug("關閉輸出流時發生異常,堆棧信息如下", e);
                }
            }
            if(in != null){
                try{
                    in.close();
                }catch(Exception e){
                    logger.debug("關閉輸入流時發生異常,堆棧信息如下", e);
                }
            }
            if(httpURLConnection != null){
                httpURLConnection.disconnect();
                httpURLConnection = null;
            }
        }
    }

    /**
     * https posp請求,可以繞過證書校驗
     * @param url
     * @param params
     * @return
     */
    public static final String sendHttpsRequestByPost(String url, Map<String,String> params) {
        String responseContent = null;
        HttpClient httpClient = new DefaultHttpClient();
        //創建TrustManager
        X509TrustManager xtm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        //這個好像是HOST驗證
        X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
            public void verify(String arg0, SSLSocket arg1) throws IOException {}
            public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {}
            public void verify(String arg0, X509Certificate arg1) throws SSLException {}
        };
        try {
            //TLS1.0與SSL3.0基本上沒有太大的差別,可粗略理解爲TLS是SSL的繼承者,但它們使用的是相同的SSLContext
            SSLContext ctx = SSLContext.getInstance("TLS");
            //使用TrustManager來初始化該上下文,TrustManager只是被SSL的Socket所使用
            ctx.init(null, new TrustManager[] { xtm }, null);
            //創建SSLSocketFactory
            SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
            socketFactory.setHostnameVerifier(hostnameVerifier);
            //通過SchemeRegistry將SSLSocketFactory註冊到我們的HttpClient上
            httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443));
            HttpPost httpPost = new HttpPost(url);
            List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>(); // 構建POST請求的表單參數
            for (String key : params.keySet()) {
                formParams.add(new BasicNameValuePair((String)key, params.get(key)));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
            //
            //CCLogUtil.print("post調用="+url);
            //CCLogUtil.print("參數="+ JSON.toJSONString(params));
            HttpResponse response = httpClient.execute(httpPost);

            HttpEntity entity = response.getEntity(); // 獲取響應實體
            if (entity != null) {
                responseContent = EntityUtils.toString(entity, "UTF-8");
                //CCLogUtil.print("返回="+responseContent);
            }
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉連接,釋放資源
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }

    /**
     * https posp請求,可以繞過證書校驗
     * @param url
     * @param params
     * @return
     */
    public static final String sendHttpsRequestByGet(String url, Map<String,String> params) {
        String responseContent = null;
        HttpClient httpClient = new DefaultHttpClient();
        //創建TrustManager
        X509TrustManager xtm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        //這個好像是HOST驗證
        X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
            public void verify(String arg0, SSLSocket arg1) throws IOException {}
            public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {}
            public void verify(String arg0, X509Certificate arg1) throws SSLException {}
        };
        try {

            //TLS1.0與SSL3.0基本上沒有太大的差別,可粗略理解爲TLS是SSL的繼承者,但它們使用的是相同的SSLContext
            SSLContext ctx = SSLContext.getInstance("TLS");
            //使用TrustManager來初始化該上下文,TrustManager只是被SSL的Socket所使用
            ctx.init(null, new TrustManager[] { xtm }, null);
            //創建SSLSocketFactory
            SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
            socketFactory.setHostnameVerifier(hostnameVerifier);
            //通過SchemeRegistry將SSLSocketFactory註冊到我們的HttpClient上
            httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443));

            /*
             * 由於GET請求的參數都是拼裝在URL地址後方,所以我們要構建一個URL,帶參數
             */
            URIBuilder uriBuilder = new URIBuilder(url);
            /** 第一種添加參數的形式 */
            if(null != params){
                for (String key : params.keySet()) {
                    uriBuilder.addParameter(key,params.get(key));
                }
            }
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            //CCLogUtil.print("get調用="+url);
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity(); // 獲取響應實體
            if (entity != null) {
                responseContent = EntityUtils.toString(entity, "UTF-8");
                //CCLogUtil.print("返回="+responseContent);
            }
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 關閉連接,釋放資源
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }



//    /**
//     * https posp請求,可以繞過證書校驗
//     * @param url
//     * @param params
//     * @return
//     */
//    public static final String sendHttpsRequestByPost(String url, Map<Object,Map.Entry> params) {
//		String responseContent = null;
//		HttpClient httpClient = new DefaultHttpClient();
//		//創建TrustManager
//		X509TrustManager xtm = new X509TrustManager() {
//			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
//			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
//			public X509Certificate[] getAcceptedIssuers() {
//				return null;
//			}
//		};
//		//這個好像是HOST驗證
//		X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
//			public boolean verify(String arg0, SSLSession arg1) {
//				return true;
//			}
//			public void verify(String arg0, SSLSocket arg1) throws IOException {}
//			public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {}
//			public void verify(String arg0, X509Certificate arg1) throws SSLException {}
//		};
//		try {
//			//TLS1.0與SSL3.0基本上沒有太大的差別,可粗略理解爲TLS是SSL的繼承者,但它們使用的是相同的SSLContext
//			SSLContext ctx = SSLContext.getInstance("TLS");
//			//使用TrustManager來初始化該上下文,TrustManager只是被SSL的Socket所使用
//			ctx.init(null, new TrustManager[] { xtm }, null);
//			//創建SSLSocketFactory
//			SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
//			socketFactory.setHostnameVerifier(hostnameVerifier);
//			//通過SchemeRegistry將SSLSocketFactory註冊到我們的HttpClient上
//			httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443));
//			HttpPost httpPost = new HttpPost(url);
//			List formParams = new ArrayList(); // 構建POST請求的表單參數
//			for (Map.Entry entry : params.entrySet()) {
//				formParams.add(new BasicNameValuePair((String)entry.getKey(), (String)entry.getValue()));
//			}
//			httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
//			HttpResponse response = httpClient.execute(httpPost);
//			HttpEntity entity = response.getEntity(); // 獲取響應實體
//			if (entity != null) {
//				responseContent = EntityUtils.toString(entity, "UTF-8");
//			}
//		} catch (KeyManagementException e) {
//			e.printStackTrace();
//		} catch (NoSuchAlgorithmException e) {
//			e.printStackTrace();
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		} catch (ClientProtocolException e) {
//			e.printStackTrace();
//		} catch (ParseException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally {
//			// 關閉連接,釋放資源
//			httpClient.getConnectionManager().shutdown();
//		}
//		return responseContent;
//	}


    /**
     * 發送HTTP_POST請求,json格式數據
     * @param url
     * @param body
     * @return
     * @throws Exception
     */
    public static String sendPostByJson(String url, String body) throws Exception {
        CloseableHttpClient httpclient = HttpClients.custom().build();
        HttpPost post = null;
        String resData = null;
        CloseableHttpResponse result = null;
        try {
            post = new HttpPost(url);
            HttpEntity entity2 = new StringEntity(body, Consts.UTF_8);
            post.setConfig(RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build());
            post.setHeader("Content-Type", "application/json");
            post.setEntity(entity2);
            result = httpclient.execute(post);
            if (HttpStatus.SC_OK == result.getStatusLine().getStatusCode()) {
                resData = EntityUtils.toString(result.getEntity());
            }
        } finally {
            if (result != null) {
                result.close();
            }
            if (post != null) {
                post.releaseConnection();
            }
            httpclient.close();
        }
        return resData;
    }

    /***
     * 獲取ip地址
     * @param request
     * @return
     */
    public static String getIPAddress(HttpServletRequest request) {
        String ip = null;

        //X-Forwarded-For:Squid 服務代理
        String ipAddresses = request.getHeader("X-Forwarded-For");

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //Proxy-Client-IP:apache 服務代理
            ipAddresses = request.getHeader("Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //WL-Proxy-Client-IP:weblogic 服務代理
            ipAddresses = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //HTTP_CLIENT_IP:有些代理服務器
            ipAddresses = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //X-Real-IP:nginx服務代理
            ipAddresses = request.getHeader("X-Real-IP");
        }

        //有些網絡通過多層代理,那麼獲取到的ip就會有多個,一般都是通過逗號(,)分割開來,並且第一個ip爲客戶端的真實IP
        if (ipAddresses != null && ipAddresses.length() != 0) {
            ip = ipAddresses.split(",")[0];
        }

        //還是不能獲取到,最後再通過request.getRemoteAddr();獲取
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    private static String localIp = null ;

    /**
     * 獲取本機ip
     * @return
     * @throws UnknownHostException
     */
    public static String getLocalIp() throws UnknownHostException{
        if(null == localIp){
            InetAddress addr = InetAddress.getLocalHost();
            String ip=addr.getHostAddress().toString(); //獲取本機ip
            localIp = ip ;
        }
        return localIp ;
    }

    /**
     * 記錄http請求相關內容
     * @param request
     * @return
     */
    public static String getHttpLog(HttpServletRequest request){
        StringBuffer sb = new StringBuffer();
        String getContextPath = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+getContextPath+"/";
        String getRemoteAddress=request.getRemoteAddr();
        String getServletPath =request.getServletPath();
        String getServletContext_getRealPath =request.getServletContext().getRealPath("/");
        String getRequestURL =request.getRequestURL().toString();
        String getRequestURI =request.getRequestURI();
        String getQueryString =request.getQueryString();
        String getRemoteUser =request.getRemoteUser();
        sb.append("getContextPath:"+ getContextPath +"<br>");
        sb.append("basePath:"+basePath+"<br>");
        sb.append("getRemoteAddress:"+ getRemoteAddress +"<br>");
        sb.append("getServletPath:"+ getServletPath +"<br>");
        sb.append("getServletContext_getRealPath:"+ getServletContext_getRealPath +"<br>");
        sb.append("getRequestURL:"+ getRequestURL +"<br>");
        sb.append("getRequestURI:"+ getRequestURI +"<br>");
        sb.append("getQueryString:"+ getQueryString +"<br>");
        sb.append("getRemoteUser:"+ getRemoteUser +"<br>");
        return sb.toString();
    }
}
<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>

使用案例1:json格式請求

使用程序調用:

參數爲jsonString

系統1調用系統2的jiekou1:

private static final String jiekou1= "http://***/api/jiekou1";

json爲前端傳來的參數(post)

JSONObject jsonobj = JSONObject.parseObject(json);
Result r = JSON.parseObject(HttpUtil.sendPostByJson(jiekou1, jsonobj.toJSONString()), Result.class);

使用案例2:使用post表單格式提交 

httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");

使用程序調用:

系統1調用系統2的jiekou2:

private static final String jiekou2= "https://***/api/jiekou2";

String param ="appid=49&length="+length+"&username="+userName+"&timestamp="+timestamp+"&signature="+(MD5.getMD5(userName + passWord + timestamp).toLowerCase());
上邊的這個參數就是拼接的一個字符串,把各個參數通過&符號拼接起來,如下示例:
String param=appid=49&length=10&username=18911069875&timestamp=1588059510&signature=87461ba750e20f85fb86096087d12f5c

Result r = JSON.parseObject(HttpUtil.sendPostRequest(jiekou2,param,true), Result.class);

注意使用postman調用時這樣傳參:



附:結果類Result.class



import java.io.Serializable;

/**
 * 返回消息
 * @author Administrator
 */
public class Result implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6978178743340116409L;
	private boolean issuccess = false;
	private String message = "";
	private String status = "";
	private Object data = null ;
	
	
	public Result(boolean isSuccess, String status, String message, Object data) {
		super();
		this.issuccess = isSuccess;
		this.status = status;
		this.message = message;
		this.data = data;
	}
	
	public boolean getIssuccess() {
		return issuccess;
	}
	public void setIssuccess(boolean isSuccess) {
		this.issuccess = isSuccess;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	@Override
	public String toString() {
		return "Result [issuccess=" + issuccess + ", message=" + message
				+ ", status=" + status + ", data=" + data + "]";
	}
	
}

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章