HttpUtils的使用、定时推送数据到不同服务的数据库

  实现定时推送数据到不同服务的数据库

首先需要准备一个HttpUtils类:

public class HttpUtils {


    public static String doPost(String URL,String jsonStr){
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        try{
            URL url = new URL(URL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            //发送POST请求必须设置为true
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(10000);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            //获取输出流
            out = new OutputStreamWriter(conn.getOutputStream());
            out.write(jsonStr);
            out.flush();
            out.close();
            //取得输入流,并使用Reader读取
            if (200 == conn.getResponseCode()){
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
                String line;
                while ((line = in.readLine()) != null){
                    result.append(line);
                    System.out.println(line);
                }
            }else{
                System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(out != null){
                    out.close();
                }
                if(in != null){
                    in.close();
                }
            }catch (IOException ioe){
                ioe.printStackTrace();
            }
        }
        return result.toString();
    }

    public static String doGet(String URL){
        HttpURLConnection conn = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuilder result = new StringBuilder();
        try{
            //创建远程url连接对象
            URL url = new URL(URL);
            //通过远程url连接对象打开一个连接,强转成HTTPURLConnection类
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(60000);
            conn.setRequestProperty("Accept", "application/json");
            //发送请求
            conn.connect();
            //通过conn取得输入流,并使用Reader读取
            if (200 == conn.getResponseCode()){
                is = conn.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
                String line;
                while ((line = br.readLine()) != null){
                    result.append(line);
                    System.out.println(line);
                }
            }else{
                System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try{
                if(br != null){
                    br.close();
                }
                if(is != null){
                    is.close();
                }
            }catch (IOException ioe){
                ioe.printStackTrace();
            }
            conn.disconnect();
        }
        return result.toString();
    }


    public static void main(String[] args) throws Exception {

        System.out.println("Testing 1 - Do Http GET request");
        doGet("http://localhost:8080/getTest?a=111&b=2222");
        System.out.println("\nTesting 2 - Do Http POST request");
        Map map = new HashMap();
        map.put("jineng","唱跳rap");
        doPost("http://localhost:8080/postTest?a=111", JSONObject.toJSONString(map));

//        System.out.println("=====================");
//        doPost("http://localhost:8080/postTest",JSONObject.toJSONString(new))
    }

}

 

然后需要在定时任务类MainTask中设置定时线程,利用Spring注解@Scheduled实现定时推送,方法中的url参数为依赖服务的对应Controller函数的映射路径

***注意:需要传递一个Json格式的字符串,注意转换,在接收时需要转换成所需Map或List***

/**
     * 每月将数据放入mysql中间表eng_person_info
     */
    @Scheduled(cron = "0 0 0 1 * ?")
    public void sendInfo() {
        Thread thread = new Thread(
                () -> {
                    List<EngPersonInfo> infoList = null;
                    try {
                        infoList = sendAttendanceService.getLastMonthInfo();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    String s = JSONArray.toJSONString(infoList);
                    log.info("------------------------------------------------------------------------------------------");
                    log.info(s);
                    HttpUtils.doPost("http://localhost:8000/postInfo", s);
                }
        );
        thread.start();
    }

 

依赖服务中的Controller层负责接受推送过来的数据,Mapping路径需要对应上面的代码

 

@PostMapping("/postRecord")
    public void postTest(@RequestBody String record) {
        System.out.println(record);
        List<EngPersonRecord> engPersonRecordList = JSONArray.parseArray(record, EngPersonRecord.class);
        System.out.println(engPersonRecordList);
        for (EngPersonRecord engPersonRecord : engPersonRecordList) {
            engPersonRecordMapper.insertOne(engPersonRecord);
        }

    }

 

 

 

 

HttpUtils的使用、定时推送数据到不同服务的数据库

上一篇:Android OpenGL ES 开发:绘制图形


下一篇:说一下Mysql索引