Java HttpUtils

import cn.hutool.http.HttpRequest;
import org.apache.commons.lang.StringUtils;

/**
 * @author: xxx
 * @date: 2023/5/13
 */
public class HttpUtils {
    /**
     * get接口默认header
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String get(String url) {
        return get(url, null, null);
    }

    /**
     * get接口,支持手动传header
     *
     * @param url
     * @param contentType
     * @param authorization
     * @return
     * @throws Exception
     */
    public static String get(String url, String contentType, String authorization) {
        HttpRequest httpRequest = HttpRequest.get(url);

        // set Content-Type
        if (StringUtils.isBlank(contentType)) {
            contentType = "application/json;charset=utf-8";
        }
        httpRequest.header("Content-Type", contentType);

        //set Authorization
        if (StringUtils.isNotBlank(authorization)) {
            httpRequest.header("Authorization", authorization);
        }

        return httpRequest.execute().body();
    }

    /**
     * post接口默认header
     *
     * @param url
     * @param body
     * @return
     * @throws Exception
     */
    public static String post(String url, String body) {
        return post(url, body, null, null);
    }

    /**
     * post接口,支持手动传header
     *
     * @param url
     * @param body
     * @param contentType
     * @param authorization
     * @return
     * @throws Exception
     */
    public static String post(String url, String body, String contentType, String authorization) {
        HttpRequest httpRequest = HttpRequest.post(url).body(body);

        // set Content-Type
        if (StringUtils.isBlank(contentType)) {
            contentType = "application/json;charset=utf-8";
        }
        httpRequest.header("Content-Type", contentType);

        //set Authorization
        if (StringUtils.isNotBlank(authorization)) {
            httpRequest.header("Authorization", authorization);
        }

        return httpRequest.execute().body();
    }
}

 

posted @ 2023-11-07 15:22  都是城市惹的祸  阅读(115)  评论(0)    收藏  举报