1. 程式人生 > 實用技巧 >記錄springboot 接入飛鵝雲印表機

記錄springboot 接入飛鵝雲印表機

使用RestTemplate請求 一直賬號有誤,後來請求頭加入APPLICATION_FORM_URLENCODED 才能訪問成功

      
  package com.***.*.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jiayuexixi.erp.entity.dto.sshop.FeiePrinterDto;
import com.jiayuexixi.erp.entity.SshopOrderItem;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : ziyue
 * @date : 2020-09-09 15:52
 * @description :
 */
@Service
public class FeiePrintApi {
    @Resource
    private RestTemplate remoteTemplate;
    private  String URL = "http://api.feieyun.cn/Api/Open/";

    private  String USER="*@*.com";
    private  String UKEY="*";

    private MultiValueMap<String, String>  setParam(String apiName){
        MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
        String STIME = String.valueOf(System.currentTimeMillis()/1000);
        map.add("user",USER);
        map.add("stime",STIME);
        map.add("sig",DigestUtils.sha1Hex(USER+UKEY+STIME));
        map.add("apiname",apiName);
        return map;
    }

    /**
     * 新增印表機
     * @param sn sn
     * @param key key
     * @param remark 說明
     * @return
     */
    public String  printerAddlist(String sn,String key,String remark){
        MultiValueMap<String, String>  map = setParam("Open_printerAddlist");
        map.add("printerContent",sn+"#"+key+"#"+remark);
        JSONObject object = getPost(map);
        JSONArray jsonArray = object.getJSONObject("data").getJSONArray("no");
        if(jsonArray==null||jsonArray.size()==0) {
            return "success";
        }
        return jsonArray.toJSONString();
    }

    public FeiePrinterDto printMsg(String sn, String content){
      return   printMsg(sn,content,1);
    }

    public FeiePrinterDto printMsg(String sn,String content,Integer times){
        MultiValueMap<String, String>  map = setParam("Open_printMsg");
        map.add("sn",sn);
        map.add("content",content);
        map.add("times",times.toString());
        JSONObject object = getPost(map);
        return JSON.toJavaObject(object, FeiePrinterDto.class);
    }




    /**
     * 傳送post 請求
     * @param map
     * @return
     */
    private JSONObject getPost( MultiValueMap<String, String>  map){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<JSONObject> requestEntity = new HttpEntity(map,headers);
        //傳送請求
        ResponseEntity<String> forEntity = remoteTemplate.postForEntity(URL,requestEntity,String.class);
        return JSONObject.parseObject(forEntity.getBody());
    }

    //orderList為陣列  b1代表名稱列佔用位元組  b2單價列 b3數量列 b4金額列-->這裡的位元組數可按自己需求自由改寫,詳細往上看112行呼叫實際例子運用
    public  String getContent(List<SshopOrderItem> sshopOrderItems,String time,Integer type, String totals, String remarks,String custInfo,int b1, int b2, int b3, int b4) {
        String orderInfo = "<CB>*****消費</CB><BR>";
        orderInfo +=type==1? " <C>(微信支付)</C><BR>":"<C>(積分支付)</C><BR>";
        orderInfo += "名稱           單價  數量 金額<BR>";
        orderInfo += "--------------------------------<BR>";
        for (int i = 0; i < sshopOrderItems.size(); i++) {
            String title = sshopOrderItems.get(i).getProdName()+"-"+sshopOrderItems.get(i).getSkuName();
            String price ="";
            String total = "";

            if(type==1) {
                 price = sshopOrderItems.get(i).getPrice().toString();
                 total=sshopOrderItems.get(i).getProductTotalAmount().toString();
            }else{
                price = sshopOrderItems.get(i).getScorePrice().toString();
                total=sshopOrderItems.get(i).getProductTotalScore().toString();
            }
            String num = sshopOrderItems.get(i).getProdCount().toString();
            price = addSpace(price, b2);
            num = addSpace(num, b3);
            total = addSpace(total, b4);
            String otherStr =  " " + price + num+ " " + total;

            int tl = 0;
            try {
                tl = title.getBytes("GBK").length;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            int spaceNum = (tl / b1 + 1) * b1 - tl;
            if (tl < b1) {
                for (int k = 0; k < spaceNum; k++) {
                    title += " ";
                }
                title += otherStr;
            } else if (tl == b1) {
                title += otherStr;
            } else {
                List<String> list = null;
                if (isEn(title)) {
                    list = getStrList(title, b1);
                } else {
                    list = getStrList(title, b1 / 2);
                }
                String s0 = titleAddSpace(list.get(0));
                // 新增 單價 數量 總額
                title = "<BR>"+s0 + otherStr + "<BR>";
                String s = "";
                for (int k = 1; k < list.size(); k++) {
                    s += list.get(k);
                }
                try {
                    s = getStringByEnter(b1, s);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                title += s;
            }
            orderInfo += title + "<BR><BR>";
        }
        orderInfo += "--------------------------------<BR>";
        orderInfo += "合計:" + totals + "<BR>";
        orderInfo += "下單時間:" + time + "<BR>";
        orderInfo += "<CB>客戶:"+custInfo+"</CB><BR>";
        if(StringUtils.isNotEmpty(remarks)) {
            orderInfo += "<CB>備註:" + remarks + "</CB><BR>";
        }
        return orderInfo;
    }
    private  String addSpace(String str, int size) {
        int len = str.length();
        if (len < size) {
            for (int i = 0; i < size - len; i++) {
                str += " ";
            }
        }
        return str;
    }
    private  Boolean isEn(String str) {
        Boolean b = false;
        try {
            b = str.getBytes("GBK").length == str.length();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return b;
    }

    private  List<String> getStrList(String inputString, int length) {
        int size = inputString.length() / length;
        if (inputString.length() % length != 0) {
            size += 1;
        }
        return getStrList(inputString, length, size);
    }

    private  List<String> getStrList(String inputString, int length, int size) {
        List<String> list = new ArrayList<String>();
        for (int index = 0; index < size; index++) {
            String childStr = substring(inputString, index * length, (index + 1) * length);
            list.add(childStr);
        }
        return list;
    }

    private static String substring(String str, int f, int t) {
        if (f > str.length()) {
            return null;
        }
        if (t > str.length()) {
            return str.substring(f, str.length());
        } else {
            return str.substring(f, t);
        }
    }
    private String titleAddSpace(String str) {
        int k=0;
        int b = 14;
        try {
            k = str.getBytes("GBK").length;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < b-k; i++) {
            str += " ";
        }
        return str;
    }
    private   String getStringByEnter(int length, String string) throws Exception {
        for (int i = 1; i <= string.length(); i++) {
            if (string.substring(0, i).getBytes("GBK").length > length) {
                return string.substring(0, i - 1) + "<BR>" + getStringByEnter(length, string.substring(i - 1));
            }
        }
        return string;
    }
}