package com.itheima.file.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.hc.client5.http.auth.AuthScope;
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;

import java.util.Base64;
import java.util.LinkedHashMap;

public class HttpClientUtils {

    public static JSONObject doPost(String postUrl, JSONObject reqBodyObj, String username, String password) {

        final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope("httpbin.org", 80),
                new UsernamePasswordCredentials(username, password.toCharArray()));

        // 设置HTTP头部
        LinkedHashMap<String, String> header = new LinkedHashMap<>();
        // header.put("Authorization", auth);
        header.put("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));

        // header.put("Authorization", baseAuth);
        header.put("Content-Type", "application/json");
        String string = reqBodyObj.toString();
        // 发送请求（这里假设HTTPHelper.sendPOST方法支持自定义头部）
        try {
            SslUtils.ignoreSsl();
            String result = HTTPHelper.sendPOST(postUrl, string, header, "UTF-8");
            System.out.println(result);
            // String 转 Map
            JSONObject resultObj = JSONObject.parseObject(result);
            return resultObj;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
