CommonController.java 10.2 KB
package com.sincere.student.controller;

import com.alibaba.fastjson.JSONObject;
import com.sincere.student.dto.BaseDto;
import com.sincere.student.dto.Province;
import com.sincere.student.dto.WxSign;
import com.sincere.student.model.AccessToken;
import com.sincere.student.model.Area;
import com.sincere.student.model.Token;
import com.sincere.student.service.CommonService;
import com.sincere.student.service.ParameterService;
import com.sincere.student.utils.HttpClientUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    CommonService commonService ;

    @Autowired
    ParameterService parameterService ;

    private static List<Area> list = new ArrayList<>();

    private static List<Province> provinces = new ArrayList<>();

    @RequestMapping(value = "GetWxSign",method = RequestMethod.GET)
    @ApiOperation(value = "获取微信分享签名")
    public BaseDto<WxSign> GetWxSign(String url){
        try {
            url = java.net.URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        url=url.replaceAll("\\+", "%2B");
        BaseDto<WxSign> result=new BaseDto<>();
//        String r=Get("http://114.55.30.100:1111/api/UserRegisterApp/GetWxShareSign","url="+url);
//        JSONObject jsonObject= JSONObject.parseObject(r);
//        String data = jsonObject.getString("result");
//        WxSign wxSign=JSON.parseObject(data,new TypeReference<WxSign>(){});
//        result.setData(wxSign);

        WxSign wxSign1=new WxSign();
        wxSign1.setTimestamp(Long.toString(System.currentTimeMillis()));
        wxSign1.setNoncestr(UUID.randomUUID().toString());
        String token = getToken();

        String js=Get("https://api.weixin.qq.com/cgi-bin/ticket/getticket","type=jsapi&access_token="+token);
        JSONObject jsonObject= JSONObject.parseObject(js);
        wxSign1.setJsapi_ticket(jsonObject.getString("ticket"));
        String rawstring = "jsapi_ticket=" + wxSign1.getJsapi_ticket() + "&noncestr=" + wxSign1.getNoncestr() + "&timestamp=" + wxSign1.getTimestamp() + "&url=" + url + "";
        wxSign1.setSignature(SHA1(rawstring));
        result.setData(wxSign1);
        return result;
    }

    @ApiOperation("省份")
    @RequestMapping(value = "getProvince",method = RequestMethod.GET)
    public List<Area> getProvince(){
        if(list.size() == 0){
            List<Area> areas = commonService.getProvince();
            for(Area area : areas){
                List<Area> cityList = commonService.getCity(area.getCode());
                if(area.getName().contains("市")){
                    //获取全部
                    area.setList(cityList);
                }else {
                    //获取4位的市
                    List<Area> trueCityList = new ArrayList<>();
                    for(Area city : cityList){
                        if(city.getCode().length() < 6){
                            trueCityList.add(city);
                        }
                    }
                    area.setList(trueCityList);
                }
            }
            list = areas ;
        }
        return list ;
    }

    @ApiOperation("省份")
    @RequestMapping(value = "getProvince2",method = RequestMethod.GET)
    public List<Province> getProvince2(){
        if(provinces.size() == 0){
            if(list.size() == 0){
                List<Area> areas = commonService.getProvince();
                for(Area area : areas){
                    List<Area> cityList = commonService.getCity(area.getCode());
                    if(area.getName().contains("市")){
                        //获取全部
                        area.setList(cityList);
                    }else {
                        //获取4位的市
                        List<Area> trueCityList = new ArrayList<>();
                        for(Area city : cityList){
                            if(city.getCode().length() < 6){
                                trueCityList.add(city);
                            }
                        }
                        area.setList(trueCityList);
                    }
                }
                list = areas ;
            }
            for(Area area : list){
                Province province = new Province() ;
                province.setValue(area.getName());
                province.setLabel(area.getName());
                List<Province> cityList = new ArrayList<>();
                for(Area city : area.getList()){
                    Province newCity = new Province();
                    newCity.setLabel(city.getName());
                    newCity.setValue(city.getName());
                    cityList.add(newCity);
                }
                province.setChildren(cityList);
                provinces.add(province);
            }
        }
        return provinces ;
    }

    @ApiOperation("市")
    @RequestMapping(value = "getCity",method = RequestMethod.GET)
    public List<Area> getCity(String code){
        return commonService.getCity(code);
    }

    @ApiOperation("高校类型")
    @RequestMapping(value = "getUniversityType",method = RequestMethod.GET)
    public List<String> getUniversityType(){
        String[] array = new String[]{"综合类","理工类","师范类","农林类","政法类","医药类"
                ,"财经类","民族类","语言类","艺术类","体育类","军事类","旅游类"};
        List<String> list =  Arrays.asList(array);
        return list ;
    }

    @ApiOperation("高校教学层次")
    @RequestMapping(value = "getUniversityLevel",method = RequestMethod.GET)
    public List<String> getUniversityLevel(){
        String[] array = new String[]{"本科","高职"};
        List<String> list =  Arrays.asList(array);
        return list ;
    }


    public static String getToken() {
        return HttpClientUtils.httpGet2("http://121.40.30.78:9903/getToken");
    }

    public String Get(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    public Token getAccessToken(String appID, String appScret) {
        Token token = new Token();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appID + "&secret="
                + appScret;
        try {
            URL getUrl=new URL(url);
            HttpURLConnection http=(HttpURLConnection)getUrl.openConnection();
            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);


            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] b = new byte[size];
            is.read(b);

            String message = new String(b, "UTF-8");
            JSONObject json = JSONObject.parseObject(message);
            token.setAccess_token(json.getString("access_token"));
            token.setExpires_in(new Integer(json.getString("expires_in")));
            System.out.println(message);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return token;
    }

    public static String SHA1(String str) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1"); //如果是SHA加密只需要将"SHA-1"改成"SHA"即可
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexStr = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexStr.append(0);
                }
                hexStr.append(shaHex);
            }
            return hexStr.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}