非常好用的HTTP請求工具類,支持Restful風格,get,post,put,delete(對接移動OneNet接口完全適用)

帶有請求頭的Get請求

不帶請求頭的GET請求

帶請求頭的POST請求

請求體是String類型,一般需要將多個請求體參數封裝成對象。可以用javaBean封裝。map封裝。List封裝。JsonObject封裝。最後轉成String

package com.ruoyi.common.utils;


import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Http請求
 *
 * @author mszhou
 */

public class HttpsUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpsUtil.class);

    private static final int TIMEOUT = 45000;
    public static final String ENCODING = "UTF-8";

    /**
     * 創建HTTP連接
     *
     * @param url              地址
     * @param method           方法 get或POST
     * @param headerParameters 頭信息 apikey
     * @param body             請求內容
     * @return
     * @throws Exception
     */
    public static HttpURLConnection createConnection(String url, String method, Map<String, String> headerParameters, String body)
            throws Exception {
        URL Url = new URL(url);
        trustAllHttpsCertificates();
        HttpURLConnection httpConnection = (HttpURLConnection) Url.openConnection();
        // 設置請求時間
        httpConnection.setConnectTimeout(TIMEOUT);
        // 設置 header
        if (headerParameters != null) {
            Iterator<String> iteratorHeader = headerParameters.keySet().iterator();
            while (iteratorHeader.hasNext()) {
                String key = iteratorHeader.next();
                String value = headerParameters.get(key);
                httpConnection.setRequestProperty(key, value);
            }
        }
        // heder請求參數爲null時,默認是application/json
        //請求類型application/json 或者 application/x-www-form-urlencoded
        httpConnection.setRequestProperty("Content-Type", "application/json;charset=" + ENCODING);

        // 設置請求方法
        httpConnection.setRequestMethod(method);
        httpConnection.setDoOutput(true);
        httpConnection.setDoInput(true);
        // 寫query數據流
        if (!(body == null || body.trim().equals(""))) {
            OutputStream writer = httpConnection.getOutputStream();
            try {
                writer.write(body.getBytes(ENCODING));
            } finally {
                if (writer != null) {
                    writer.flush();
                    writer.close();
                }
            }
        }

        // 請求結果
        int responseCode = httpConnection.getResponseCode();
        if (responseCode != 200) {
            throw new Exception(responseCode + ":" + inputStream2String(
                    httpConnection.getErrorStream(), ENCODING));
        }
        return httpConnection;
    }

    /**
     * 將參數化爲 body
     *
     * @param params
     * @return
     */
    public static String getRequestBody(Map<String, String> params) {
        return getRequestBody(params, true);
    }

    /**
     * 將參數化爲 body
     * 將Map集合中的鍵值多轉成url參數的樣式objInstId=0&executeResId=5505&objId=3200&imei=869976030098439
     *
     * @param params
     * @return
     */
    public static String getRequestBody(Map<String, String> params, boolean urlEncode) {
        StringBuilder body = new StringBuilder();

        Iterator<String> iteratorHeader = params.keySet().iterator();
        while (iteratorHeader.hasNext()) {
            String key = iteratorHeader.next();
            String value = params.get(key);
            if (urlEncode) {
                try {
                    body.append(key + "=" + URLEncoder.encode(value, ENCODING) + "&");
                } catch (UnsupportedEncodingException e) {

                }
            } else {
                body.append(key + "=" + value + "&");
            }
        }
        if (body.length() == 0) {
            return "";
        }
        String strbody = body.substring(0, body.length() - 1);
        return strbody;
    }


    /**
     * 帶有請求頭的POST請求
     *
     * @param address 請求地址 url
     * @param header  請求頭參數apikey
     * @param body    請求體 一般是將javaBean對象,map對象轉成json字符串
     * @return
     * @throws Exception
     */
    public static String post(String address, Map<String, String> header, String body) throws Exception {
        //參數1:url請求地址。參數2:POST方法 。參數3:頭信息"api-key=PkbXWxmDv0zG48sWdnr9P=BLJPs=" 參數4:body請求體
        String proxyHttpRequest = proxyHttpRequest(address, "POST", header, body);
        return proxyHttpRequest;
    }
    
    /**
     * 不帶請求頭的Get請求
     *
     * @param address    接口URL
     * @param parameters ?後面的請求參數
     * @return
     * @throws Exception
     */
    public static String get(String address, Map<String, String> parameters) throws Exception {
        //參數1:請求URL和?後面的參數,參數2:請求方式GET,參數3:請求頭。請求體:GET請求爲NULL,用於POST請求
        return proxyHttpRequest(address + "?"
                + getRequestBody(parameters), "GET", null, null);
    }

    /**
     * 帶請求頭的Get請求
     *
     * @param address    接口URL
     * @param parameters ?後面的請求參數
     * @param header     請求頭 header
     * @return
     * @throws Exception
     */
    public static String doGet(String address, Map<String, String> parameters, Map<String, String> header) throws Exception {
        //參數1:請求URL和?後面的參數。參數2:請求方式GET。參數3:請求頭。請求體:GET請求爲NULL,用於POST請求
        return proxyHttpRequest(address + "?"
                + getRequestBody(parameters), "GET", header, null);
    }

    /**
     * Delete請求,刪除
     * @param address 請求地址 url http://api.heclouds.com/devices/123455254
     * @param header 請求頭參數
     * @return
     * @throws Exception
     */
    public static String delete(String address, Map<String, String> header) throws Exception {
        //參數1:url請求地址。參數2:POST方法 。參數3:頭信息"api-key=PkbXWxmDv0zG48sWdnr9P=BLJPs=" 參數4:body請求體
        String proxyHttpRequest = proxyHttpRequest(address, "DELETE", header, null);
        return proxyHttpRequest;
    }

    /**
     * PUT請求的更新操作
     * @param address 請求URL樣式 http://api.heclouds.com/devices/580959234
     * @param header 請求頭
     * @param body 請求體
     * @return
     * @throws Exception
     */
    public static String put(String address, Map<String, String> header,String body) throws Exception {
        //參數1:url請求地址。參數2:POST方法 。參數3:頭信息"api-key=PkbXWxmDv0zG48sWdnr9P=BLJPs=" 參數4:body請求體
        String proxyHttpRequest = proxyHttpRequest(address, "PUT", header, body);
        return proxyHttpRequest;
    }

    /**
     * 讀取網絡文件
     *
     * @param address
     * @param headerParameters
     * @param file
     * @return
     * @throws Exception
     */
    public static String getFile(String address,
                                 Map<String, String> headerParameters, File file) throws Exception {
        String result = "fail";

        HttpURLConnection httpConnection = null;
        try {
            httpConnection = createConnection(address, "POST", null,
                    getRequestBody(headerParameters));
            result = readInputStream(httpConnection.getInputStream(), file);

        } catch (Exception e) {
            throw e;
        } finally {
            if (httpConnection != null) {
                httpConnection.disconnect();
            }

        }

        return result;
    }

    public byte[] getFileByte(String address,
                              Map<String, String> headerParameters) throws Exception {
        byte[] result = null;

        HttpURLConnection httpConnection = null;
        try {
            httpConnection = createConnection(address, "POST", null,
                    getRequestBody(headerParameters));
            result = readInputStreamToByte(httpConnection.getInputStream());

        } catch (Exception e) {
            throw e;
        } finally {
            if (httpConnection != null) {
                httpConnection.disconnect();
            }

        }

        return result;
    }

    /**
     * 讀取文件流
     *
     * @param in
     * @return
     * @throws Exception
     */
    public static String readInputStream(InputStream in, File file)
            throws Exception {
        FileOutputStream out = null;
        ByteArrayOutputStream output = null;

        try {
            output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }

            out = new FileOutputStream(file);
            out.write(output.toByteArray());

        } catch (Exception e) {
            throw e;
        } finally {
            if (output != null) {
                output.close();
            }
            if (out != null) {
                out.close();
            }
        }
        return "success";
    }

    public byte[] readInputStreamToByte(InputStream in) throws Exception {
        FileOutputStream out = null;
        ByteArrayOutputStream output = null;
        byte[] byteFile = null;

        try {
            output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }
            byteFile = output.toByteArray();
        } catch (Exception e) {
            throw e;
        } finally {
            if (output != null) {
                output.close();
            }
            if (out != null) {
                out.close();
            }
        }

        return byteFile;
    }

    /**
     * HTTP請求
     *
     * @param address          地址
     * @param method           指明是get或post
     * @param headerParameters 請求頭信息
     * @param body             請求內容 多個參數時,將對象轉成json字符串
     * @return
     * @throws Exception
     */
    public static String proxyHttpRequest(String address, String method, Map<String, String> headerParameters, String body) throws Exception {
        String result = null;
        HttpURLConnection httpConnection = null;

        try {
            //參數1 地址。參數2 get或post  參數3:頭信息  參數4 url參數 請求內容
            httpConnection = createConnection(address, method, headerParameters, body);

            String encoding = "UTF-8";
            if (httpConnection.getContentType() != null && httpConnection.getContentType().indexOf("charset=") >= 0) {
                encoding = httpConnection.getContentType().substring(
                        httpConnection.getContentType().indexOf("charset=") + 8);
            }
            result = inputStream2String(httpConnection.getInputStream(), encoding);
            logger.info("HTTPproxy response: {},{}", address, result.toString());

        } catch (Exception e) {
            logger.info("HTTPproxy error: {}", e.getMessage());
            throw e;
        } finally {
            if (httpConnection != null) {
                httpConnection.disconnect();
            }
        }
        return result;
    }


    /**
     * 讀取inputStream 到 string
     *
     * @param input
     * @param encoding
     * @return
     * @throws IOException
     */
    private static String inputStream2String(InputStream input, String encoding)
            throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input,
                encoding));
        StringBuilder result = new StringBuilder();
        String temp = null;
        while ((temp = reader.readLine()) != null) {
            result.append(temp);
        }

        return result.toString();

    }


    /**
     * 設置 https 請求
     *
     * @throws Exception
     */
    public static void trustAllHttpsCertificates() throws Exception {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String str, SSLSession session) {
                return true;
            }
        });
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
                .getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc
                .getSocketFactory());
    }


    //設置 https 請求證書
    static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }


    }

    //====================================================================
    //============================= 測試調用   ============================
    //====================================================================
    public static void main0(String[] args) {

        try {
            //請求地址(我這裏測試使用淘寶提供的手機號碼信息查詢的接口)
            String address = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
            //get請求的請求參數
            Map<String, String> params = new HashMap<String, String>();
            params.put("tel", "13791086826");
            //不帶有請求頭的get請求
            String res = HttpsUtil.get(address, params);
            System.out.println(res);//打印返回參數
        } catch (Exception e) {
            // TODO 異常
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception {
        //封裝請求頭
        Map<String, String> header = new HashMap<String, String>();
        header.put("api-key", "PkbXWxmD23v0233zG42323dnr9232323s=");

        String url = "https://api.heclouds.com/devices";
        //get請求的請求參數
        Map<String, String> params = new HashMap<String, String>();
        params.put("device_id", "576833338");
        //帶有請求頭的get請求
        String s = HttpsUtil.doGet(url, params, header);
        System.out.println(s);

        String url1 = "https://api.heclouds.com/devices/getbyimei";
        //get請求的請求參數
        Map<String, String> params1 = new HashMap<String, String>();
        params1.put("imei", "8606400408122333");
        //帶有請求頭的get請求
        String s1 = HttpsUtil.doGet(url1, params1, header);
        System.out.println(s1);

        //delete請求,刪除設備
        String device_id="5349233336";
        String url2 = "https://api.heclouds.com/devices/"+device_id;
         //帶有請求頭的Delete請求
         String s2 = HttpsUtil.delete(url2, header);
         System.out.println(s2);

        //put請求,更新設備
        String deviceId="580933393";
        String url3 = "https://api.heclouds.com/devices/"+deviceId;
        Map<String, String> body = new HashMap<String, String>();
        body.put("title","aaaa");
        HttpsUtil.put(url3,header,JSON.toJSONString(body));

    }

    /**
     * 帶有請求頭的post方式示例
     *
     * @param args
     */
    public static void main3(String[] args) {
        try {
            String url = "https://api.dtuip.com/qy/user/login.html";
            Map<String, String> header = new HashMap<String, String>();
            header.put("Content-Type", "application/json");
            Map<String, String> body = new HashMap<String, String>();
            body.put("userName", "11239112233");
            body.put("password", "123443455");
            String mapJsonString = JSON.toJSONString(body);
            String postResu = HttpsUtil.post(url, null, mapJsonString);
            System.out.println(postResu);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
發佈了99 篇原創文章 · 獲贊 41 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章