package com.bohuikeji.frame.module.admin.utils;

import jodd.http.HttpRequest;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;

/**
 * 网络工具请求类
 * @author 10552
 * 【警告】该类已废弃，网络请求请使用：jodd.http框架  文档位于：https://jodd.org/http
 *
 * 【简单使用示例如下：】
 *     HttpRequest httpRequest = HttpRequest.get("https://oss.bhynm.com/delivery/upload/2020/2/23/158243347169490.jpg");
 *     HttpResponse response = httpRequest.send();
 */
@Deprecated
public class HttpUtils {
    private final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
    /**
     * 获取QuickHttp实例
     * @return
     */
    public static HttpRequest getHttpClient(){
        return  HttpClientHolder.quickHttp;
    }

    /**
     * 单例内部类
     */
    private static class HttpClientHolder {
        private static HttpRequest quickHttp;
        static {
            quickHttp=new HttpRequest();
        }
    }

    public static String doGet(String urlPath, Map<String, String> params) {
        return HttpRequest.get(urlPath).query(params).send().bodyText();
    }

    /**
     * Post JOSN
     * @param url
     * @param json
     * @return
     */
    public static String post(String url, String json) {
        logger.info("Post URL=" + url);
        logger.info("Post Data=" + json);

        StringBuffer requestText = new StringBuffer();

        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        HttpPost httpPost = new HttpPost(url);
        StringEntity entityParams = null;
        try {
            entityParams = new StringEntity(json, "utf-8");
            httpPost.setEntity(entityParams);
            httpPost.setHeader("Content-Type", "type/json;charset=ISO-8859-1");
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            byte[] x = EntityUtils.toByteArray(response.getEntity());
            requestText.append(new String(x, "utf-8"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            logger.info("Request=" + requestText.toString());
        }
        return requestText.toString();
    }
}
