Java 發送 Https 請求工具類 (兼容http)


 

依賴 jsoup-1.11.3.jar

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.11.3</version>
</dependency>

 

 

HttpUtils.java

package javax.utils;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;

/**
 * Http發送post請求工具,兼容http和https兩種請求類型
 */
public class HttpUtils {

    /**
     * 請求超時時間
     */
    private static final int TIME_OUT = 120000;

    /**
     * Https請求
     */
    private static final String HTTPS = "https";

    /**
     * Content-Type
     */
    private static final String CONTENT_TYPE = "Content-Type";

    /**
     * 表單提交方式Content-Type
     */
    private static final String FORM_TYPE = "application/x-www-form-urlencoded;charset=UTF-8";

    /**
     * JSON提交方式Content-Type
     */
    private static final String JSON_TYPE = "application/json;charset=UTF-8";

    /**
     * 發送Get請求
     * 
     * @param url 請求URL
     * @return HTTP響應對象
     * @throws IOException 程序異常時拋出,由調用者處理
     */
    public static Response get(String url) throws IOException {
        return get(url, null);
    }

    /**
     * 發送Get請求
     * 
     * @param url 請求URL
     * @param headers 請求頭參數
     * @return HTTP響應對象
     * @throws IOException 程序異常時拋出,由調用者處理
     */
    public static Response get(String url, Map<String, String> headers) throws IOException {
        if (null == url || url.isEmpty()) {
            throw new RuntimeException("The request URL is blank.");
        }

        // 如果是Https請求
        if (url.startsWith(HTTPS)) {
            getTrust();
        }
        Connection connection = Jsoup.connect(url);
        connection.method(Method.GET);
        connection.timeout(TIME_OUT);
        connection.ignoreHttpErrors(true);
        connection.ignoreContentType(true);
        connection.maxBodySize(0);

        if (null != headers) {
            connection.headers(headers);
        }

        Response response = connection.execute();
        return response;
    }

    /**
     * 發送JSON格式參數POST請求
     * 
     * @param url 請求路徑
     * @param params JSON格式請求參數
     * @return HTTP響應對象
     * @throws IOException 程序異常時拋出,由調用者處理
     */
    public static Response post(String url, String params) throws IOException {
        return doPostRequest(url, null, params);
    }

    /**
     * 發送JSON格式參數POST請求
     * 
     * @param url 請求路徑
     * @param headers 請求頭中設置的參數
     * @param params JSON格式請求參數
     * @return HTTP響應對象
     * @throws IOException 程序異常時拋出,由調用者處理
     */
    public static Response post(String url, Map<String, String> headers, String params) throws IOException {
        return doPostRequest(url, headers, params);
    }

    /**
     * 字符串參數post請求
     * 
     * @param url 請求URL地址
     * @param paramMap 請求字符串參數集合
     * @return HTTP響應對象
     * @throws IOException 程序異常時拋出,由調用者處理
     */
    public static Response post(String url, Map<String, String> paramMap) throws IOException {
        return doPostRequest(url, null, paramMap, null);
    }

    /**
     * 帶請求頭的普通表單提交方式post請求
     * 
     * @param headers 請求頭參數
     * @param url 請求URL地址
     * @param paramMap 請求字符串參數集合
     * @return HTTP響應對象
     * @throws IOException 程序異常時拋出,由調用者處理
     */
    public static Response post(Map<String, String> headers, String url, Map<String, String> paramMap) throws IOException {
        return doPostRequest(url, headers, paramMap, null);
    }

    /**
     * 帶上傳文件的post請求
     * 
     * @param url 請求URL地址
     * @param paramMap 請求字符串參數集合
     * @param fileMap 請求文件參數集合
     * @return HTTP響應對象
     * @throws IOException 程序異常時拋出,由調用者處理
     */
    public static Response post(String url, Map<String, String> paramMap, Map<String, File> fileMap) throws IOException {
        return doPostRequest(url, null, paramMap, fileMap);
    }

    /**
     * 帶請求頭的上傳文件post請求
     * 
     * @param url 請求URL地址
     * @param headers 請求頭參數
     * @param paramMap 請求字符串參數集合
     * @param fileMap 請求文件參數集合
     * @return HTTP響應對象
     * @throws IOException 程序異常時拋出,由調用者處理
     */
    public static Response post(String url, Map<String, String> headers, Map<String, String> paramMap, Map<String, File> fileMap) throws IOException {
        return doPostRequest(url, headers, paramMap, fileMap);
    }

    /**
     * 執行post請求
     * 
     * @param url 請求URL地址
     * @param headers 請求頭
     * @param jsonParams 請求JSON格式字符串參數
     * @return HTTP響應對象
     * @throws IOException 程序異常時拋出,由調用者處理
     */
    private static Response doPostRequest(String url, Map<String, String> headers, String jsonParams) throws IOException {
        if (null == url || url.isEmpty()) {
            throw new RuntimeException("The request URL is blank.");
        }

        // 如果是Https請求
        if (url.startsWith(HTTPS)) {
            getTrust();
        }

        Connection connection = Jsoup.connect(url);
        connection.method(Method.POST);
        connection.timeout(TIME_OUT);
        connection.ignoreHttpErrors(true);
        connection.ignoreContentType(true);
        connection.maxBodySize(0);

        if (null != headers) {
            connection.headers(headers);
        }

        connection.header(CONTENT_TYPE, JSON_TYPE);
        connection.requestBody(jsonParams);

        Response response = connection.execute();
        return response;
    }

    /**
     * 普通表單方式發送POST請求
     * 
     * @param url 請求URL地址
     * @param headers 請求頭
     * @param paramMap 請求字符串參數集合
     * @param fileMap 請求文件參數集合
     * @return HTTP響應對象
     * @throws IOException 程序異常時拋出,由調用者處理
     */
    private static Response doPostRequest(String url, Map<String, String> headers, Map<String, String> paramMap, Map<String, File> fileMap) throws IOException {
        if (null == url || url.isEmpty()) {
            throw new RuntimeException("The request URL is blank.");
        }

        // 如果是Https請求
        if (url.startsWith(HTTPS)) {
            getTrust();
        }

        Connection connection = Jsoup.connect(url);
        connection.method(Method.POST);
        connection.timeout(TIME_OUT);
        connection.ignoreHttpErrors(true);
        connection.ignoreContentType(true);
        connection.maxBodySize(0);

        if (null != headers) {
            connection.headers(headers);
        }

        // 收集上傳文件輸入流,最終全部關閉
        List<InputStream> inputStreamList = null;
        try {

            // 添加文件參數
            if (null != fileMap && !fileMap.isEmpty()) {
                inputStreamList = new ArrayList<InputStream>();
                InputStream in = null;
                File file = null;
                for (Entry<String, File> e : fileMap.entrySet()) {
                    file = e.getValue();
                    in = new FileInputStream(file);
                    inputStreamList.add(in);
                    connection.data(e.getKey(), file.getName(), in);
                }
            }

            // 普通表單提交方式
            else {
                connection.header(CONTENT_TYPE, FORM_TYPE);
            }

            // 添加字符串類參數
            if (null != paramMap && !paramMap.isEmpty()) {
                connection.data(paramMap);
            }

            Response response = connection.execute();
            return response;
        }

        // 關閉上傳文件的輸入流
        finally {
            closeStream(inputStreamList);
        }
    }

    /**
     * 關流
     * 
     * @param streamList 流集合
     */
    private static void closeStream(List<? extends Closeable> streamList) {
        if (null != streamList) {
            for (Closeable stream : streamList) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 獲取服務器信任
     */
    private static void getTrust() {
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new X509TrustManager[] { new 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[0];
                }
            } }, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 

 

 

 

.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM