UnirestUtils工具類,封裝常用的get和post請求,並支持代理設置


pom.xml新增如下依賴

<dependency>
    <groupId>com.konghq</groupId>
    <artifactId>unirest-java</artifactId>
    <version>3.7.02</version>
 </dependency>

 

UnirestUtils.java

package com.geostar.gfstack.monitorcenter.client.util;

import kong.unirest.GetRequest;
import kong.unirest.HttpRequestWithBody;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import lombok.Builder;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * UnirestUtils工具類,封裝常用的get和post請求,並支持代理設置
 */
@Builder
public class UnirestUtils {

    /**
     * 默認編碼格式
     */
    private static final String DEFAULT_ENCODING = "UTF-8";
    /**
     * 代理是否開啟
     */
    private boolean openProxy;

    /**
     * 代理主機
     */
    private String proxyHost;

    /**
     * 代理端口
     */
    private int proxyPort;

    /**
     * URL前綴
     */
    private String urlPrefix;

    /**
     * 默認請求頭
     */
    private Map<String, String> defaultHeader;

    /**
     * json請求頭,Content-Type: application/json
     */
    public static Map<String, String> header_JSON;

    /**
     * form請求頭,Content-Type: application/x-www-form-urlencoded
     */
    public static Map<String, String> header_FORM;

    static {
        header_JSON = new HashMap<String, String>() {{
            put("Content-Type", "application/json");
        }};
        header_FORM = new HashMap<String, String>() {{
            put("Content-Type", "application/x-www-form-urlencoded");
        }};
    }

    /**
     * 設置代理
     *
     * @param host 代理主機
     * @param port 代理端口
     */
    public UnirestUtils proxy(String host, Integer port) {
        proxyHost = host;
        proxyPort = port;
        openProxy = true;
        return this;
    }

    /**
     * 設置代理
     *
     * @param host 代理主機
     * @param port 代理端口
     * @param open 代理是否開啟
     */
    public UnirestUtils proxy(String host, Integer port, boolean open) {
        proxyHost = host;
        proxyPort = port;
        openProxy = open;
        return this;
    }

    /**
     * get請求
     *
     * @param url 請求地址
     * @return
     */
    public String get(String url) {
        return get(url, null, defaultHeader);
    }

    /**
     * get請求
     *
     * @param url    請求地址
     * @param params 請求參數
     * @return
     */
    public String get(String url, Map<String, Object> params) {
        return get(url, params, defaultHeader);
    }

    /**
     * get請求
     *
     * @param url     請求地址
     * @param params  請求參數
     * @param headers 請求頭
     * @return
     */
    public String get(String url, Map<String, Object> params, Map<String, String> headers) {
        url = processUrl(url);
        GetRequest getRequest = Unirest.get(url);
        if (openProxy) {
            getRequest.proxy(proxyHost, proxyPort);
        }
        if (params != null && params.size() > 0) {
            for (String s : params.keySet()) {
                getRequest.queryString(s, params.get(s));
            }
        }
        if (headers != null && headers.size() > 0) {
            for (String s : headers.keySet()) {
                getRequest.header(s, headers.get(s));
            }
        }
        HttpResponse<String> response = getRequest.asString();
        return response.getBody();
    }

    /**
     * post請求
     *
     * @param url 請求地址
     * @return
     */
    public String post(String url) {
        return post(url, null, defaultHeader);
    }

    /**
     * post請求
     *
     * @param url     請求地址
     * @param payload 請求body
     * @return
     */
    public String post(String url, String payload) {
        return post(url, payload, defaultHeader);
    }

    /**
     * post請求
     *
     * @param url     請求地址
     * @param headers 請求頭
     * @return
     */
    public String post(String url, Map<String, String> headers) {
        return post(url, null, headers);
    }

    /**
     * post請求
     *
     * @param url     請求地址
     * @param payload 請求body
     * @param headers 請求頭
     * @return
     */
    public String post(String url, String payload, Map<String, String> headers) {
        url = processUrl(url);
        HttpRequestWithBody httpRequestWithBody = Unirest.post(url);
        if (openProxy) {
            httpRequestWithBody.proxy(proxyHost, proxyPort);
        }
        if (headers != null && headers.size() > 0) {
            for (String s : headers.keySet()) {
                httpRequestWithBody.header(s, headers.get(s));
            }
        }
        if (payload == null) {
            return httpRequestWithBody.asString().getBody();
        } else {
            return httpRequestWithBody.body(payload).asString().getBody();
        }
    }

    /**
     * 處理url
     *
     * @param url 原始url,如urlPrefix不為空,則會在url前補上urlPrefix
     * @return
     */
    private String processUrl(String url) {
        if (urlPrefix != null) {
            url = urlPrefix + url;
        }
        return url;
    }

    /**
     * uri編碼,默認采用UTF-8編碼
     *
     * @param text 編碼前的文本
     * @return
     */
    public static String encodeURIComponent(String text) {
        return encodeURIComponent(text, DEFAULT_ENCODING);
    }

    /**
     * uri編碼
     *
     * @param text     編碼前的文本
     * @param encoding 編碼格式
     * @return
     */
    public static String encodeURIComponent(String text, String encoding) {
        try {
            return URLEncoder.encode(text, encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return text;
        }
    }

    /**
     * uri解碼,默認采用UTF-8解碼
     *
     * @param text 解碼前的文本
     * @return
     */
    public static String decodeURIComponent(String text) {
        return decodeURIComponent(text, DEFAULT_ENCODING);
    }

    /**
     * uri解碼
     *
     * @param text     解碼前的文本
     * @param encoding 編碼格式
     * @return
     */
    public static String decodeURIComponent(String text, String encoding) {
        try {
            return URLDecoder.decode(text, encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return text;
        }
    }

    /**
     * 測試main函數
     *
     * @param args
     */
    public static void main(String[] args) {
        UnirestUtils utils = UnirestUtils.builder().proxyHost("localhost").proxyPort(8888).openProxy(true).build();
        System.out.println(utils.get("http://www.baidu.com"));
    }

}

  


免責聲明!

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



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