package org.jeecg.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;

/**
 * 功能描述：SAP接口调用
 *
 * @Author: chenchuang
 * @Date: 2022/1/25 14:59
 */
public class InterfaceConnUtils {
    /**
     * post请求-推数据
     */
    public static JSONObject doPost(JSONObject json, String url) {
        //定义测试返回JSON
        JSONObject onejb = new JSONObject();
        HttpClient httpClient = new DefaultHttpClient();
//        HttpPost httpPost=new HttpPost("http://erpdev01.saplogin.freshhema.com:8000/sap/bc/zapi_inbound?sap-client=300");
//        HttpPost httpPost=new HttpPost("http://139.196.226.160:8000/sap/bc/zapi_inbound?sap-client=710");
        HttpPost httpPost=new HttpPost("http://139.196.199.214:8000/sap/bc/zapi_inbound?sap-client=800");
        httpPost.setHeader("Content-Type", "application/json");
        String tokenCode = "sap:Cwa1QJrhfhtXbzSGZi94ydBPNQCPbmz7";
        //使用base64进行加密
        byte[] tokenByte = Base64.encodeBase64((tokenCode).getBytes());
        //将加密的信息转换为string
        String tokenStr = new String(tokenByte);
        //Basic
        String token = "Basic "+tokenStr;
        String encoding="";
        try {
//            encoding = DatatypeConverter.printBase64Binary("ZKANB01:Aa12345678".getBytes("UTF-8"));
            encoding = DatatypeConverter.printBase64Binary("ZKANB01:Kb6a5553ec90a".getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //把认证信息发到header中
//        httpPost.setHeader("Authorization", "Basic "+token);
        httpPost.setHeader("Authorization", "Basic "+encoding);

        //result
        //JSONObject  backjson=new JSONObject();
        //backjson.put("data", json);
        StringEntity entity;
        entity = new StringEntity(json.toString(),"utf-8");
        entity.setContentEncoding("utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        try {
            //调用接口
            HttpResponse response = httpClient.execute(httpPost);
            //返回信息
            String resultStr = EntityUtils.toString(response.getEntity(),"UTF-8");
            onejb=JSONObject.parseObject(resultStr);
            System.out.println("返回消息内容："+onejb);
            // jf.put("head",JsonChangeUtils.testJson(mapList));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return onejb;
    }
}
