package com.kmall.api.service;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

@Service
public class ApiKD100Service {

    //电商加密私钥，快递鸟提供，注意保管，不要泄漏
    private String AppKey = "f7a8d954da86787b";
    //请求url
    private String ReqURL = "http://www.kuaidi100.com/applyurl?key=APPKEY&com=expCode&nu=expNo";

    /**
     * Json方式 查询订单物流轨迹
     *
     * @throws Exception
     */
    public String getOrderTracesByJson(String expCode, String expNo) {
        String url = ReqURL.replace("APPKEY", AppKey).replace("expCode", expCode).replace("expNo", expNo);
        String html = sendGet(url);
        return html;
    }

    public String sendGet(String urlStr) {
        String result = "";
        try {
            URL url = new URL(urlStr);
            URLConnection con = url.openConnection();
            con.setAllowUserInteraction(false);
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type","text/html; charset=UTF-8");
            InputStream urlStream = url.openStream();
            String type = con.guessContentTypeFromStream(urlStream);
            String charSet = null;
            if (type == null)
                type = con.getContentType();

            if (type == null || type.trim().length() == 0 || type.trim().indexOf("text/html") < 0)
                return null;

            if (type.indexOf("charset=") > 0)
                charSet = type.substring(type.indexOf("charset=") + 8);

            byte b[] = new byte[10000];
            int numRead = urlStream.read(b);
            result = new String(b, 0, numRead);
            while (numRead != -1) {
                numRead = urlStream.read(b);
                if (numRead != -1) {
                    String newContent = new String(b, 0, numRead, charSet);
                    result += newContent;
                }
            }
            //System.out.println("content:" + content);
            urlStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
