zoukankan      html  css  js  c++  java
  • 从节假日api查询数据并插入到数据库代码实例

    只关注main方法即可,下载到本地更改包名即可使用,如不需要插入数据库,可注释掉JDBC相关。api返回值:0工作日,1休息日,2节假日

    package cn.com.ebidding;
    import net.sf.json.JSONObject;
    
    import org.apache.commons.httpclient.*;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.apache.commons.httpclient.params.HttpMethodParams;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    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 com.mysql.jdbc.Connection;
    import com.mysql.jdbc.PreparedStatement;
    
    import java.io.IOException;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.Calendar;
    
    /**
     * Created by liqun.chen on 2017/5/15.
     */
    public class HttpUtil {
        /**
         * json 字符串
         * @param url
         * @param param
         * @return
         */
        public static String getSerchPersion(String url,String param){
          /* 1 生成 HttpClinet 对象并设置参数 */
            HttpClient httpClient = new HttpClient();
            // 设置 Http 连接超时为5秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
          /* 2 生成 GetMethod 对象并设置参数 */
            GetMethod getMethod = new GetMethod(url);
            // 设置 get 请求超时为 5 秒
            getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
            // 设置请求重试处理,用的是默认的重试处理:请求三次
            getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
            String response = "";
          /* 3 执行 HTTP GET 请求 */
            try {
                int statusCode = httpClient.executeMethod(getMethod);
             /* 4 判断访问的状态码 */
                if (statusCode != HttpStatus.SC_OK) {
                    System.err.println("请求出错: "+ getMethod.getStatusLine());
                }
             /* 5 处理 HTTP 响应内容 */
                // HTTP响应头部信息,这里简单打印
                Header[] headers = getMethod.getResponseHeaders();
                for (Header h : headers)
                    System.out.println(h.getName() + "------------ " + h.getValue());
                // 读取 HTTP 响应内容,这里简单打印网页内容
                byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组
                response = new String(responseBody, param);
                System.out.println("----------response:" + response);
                // 读取为 InputStream,在网页内容数据量大时候推荐使用
                // InputStream response = getMethod.getResponseBodyAsStream();
            } catch (HttpException e) {
                // 发生致命的异常,可能是协议不对或者返回的内容有问题
                System.out.println("请检查输入的URL!");
                e.printStackTrace();
            } catch (IOException e) {
                // 发生网络异常
                System.out.println("发生网络异常!");
                e.printStackTrace();
            } finally {
             /* 6 .释放连接 */
                getMethod.releaseConnection();
            }
            return response;
        }
        /**
         * post请求
         * @param url
         * @param json
         * @return
         */
        public static JSONObject doPost(String url,JSONObject json){
            DefaultHttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            JSONObject response = null;
            try {
                StringEntity s = new StringEntity(json.toString());
                s.setContentEncoding("UTF-8");
                s.setContentType("application/json");//发送json数据需要设置contentType
                post.setEntity(s);
                HttpResponse res = client.execute(post);
                if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                    HttpEntity entity = res.getEntity();
                    String result = EntityUtils.toString(res.getEntity());// 返回json格式:
                   
                    try {
                        response = JSONObject.fromObject(result);
                    } catch (Exception e) {
                        response=new JSONObject().accumulate("key", result.toString());
                    }
                    
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return response;
        }
        private static Connection getConn() {
            String driver = "com.mysql.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/cec_dev";
            String username = "root";
            String password = "123456";
            Connection conn = null;
            try {
                Class.forName(driver); //classLoader,加载对应驱动
                conn = (Connection) DriverManager.getConnection(url, username, password);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return conn;
        }
        private static int deleted( ) {
            Connection conn = getConn();
            int i = 0;
            String sql = "DELETE FROM sys_holiday";
            PreparedStatement pstmt;
            try {
                pstmt = (PreparedStatement) conn.prepareStatement(sql);
               
                i = pstmt.executeUpdate();
                pstmt.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return i;
        }
        private static int insert( String year,String m,String d,String holiday) {
            Connection conn = getConn();
            int i = 0;
            String sql = "INSERT INTO sys_holiday (YEAR,MONTH,DAY,holiday) VALUES(?,?,?,?)";
            PreparedStatement pstmt;
            try {
                pstmt = (PreparedStatement) conn.prepareStatement(sql);
                pstmt.setString(1, year);
                pstmt.setString(2, m);
                pstmt.setString(3, d);
                pstmt.setString(4, holiday);
                i = pstmt.executeUpdate();
                pstmt.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return i;
        }
      //调用
        public static void main(String arg[]) throws Exception {
            deleted();
            Calendar now =Calendar.getInstance();
            now.set(now.get(now.YEAR), 01, 01);
            for (int i = 0; i < 400; i++) {
                
                String y=String.valueOf(now.get(now.YEAR));
                String m=String.valueOf(now.get(now.MONTH)+1);
                String d=String.valueOf(now.get(now.DATE));
                if (m.length()==1) {
                    m="0"+m;
                }
                if (d.length()==1) {
                    d="0"+d;
                }
                
                   String url = "http://tool.bitefu.net/jiari/?d="+y+m+d;
                 
                    System.out.println(url);
                    JSONObject params = new JSONObject();
                    
    
    
                    //post 请求
                    JSONObject jsonObject = doPost(url,params);
                    System.out.println(jsonObject.toString());
                    System.out.println(jsonObject.get("key").toString());
                    insert(y, m, d,jsonObject.get("key").toString() );
                    now.add(now.DATE, 1);
            }
            
            }
    }
  • 相关阅读:
    node.js模块本地代理模块(将自己本机/局域网)服务 代理到外网可以访问
    node.js基本概念简单解释
    RN 使用第三方组件之react-native-image-picker(拍照/从相册获取图片)
    RN 上传文件到以及上传文件到七牛云(初步)
    【HTML+CSS+JavaScript+Bootstrap+Vue】选项卡(两种方式)
    【HTML+CSS+JavaScript+Bootstrap+Vue】登录(获取表单数据)
    【HTML+CSS+JavaScript+Bootstrap+Vue】待办事项
    第六章 前端开发——Vue框架
    第五章 前端开发——Boostrap
    【HTML+CSS+JavaScript(jQuery)】轮播图
  • 原文地址:https://www.cnblogs.com/zhanglixuan/p/10552551.html
Copyright © 2011-2022 走看看