zoukankan      html  css  js  c++  java
  • API

    <script type="text/javascript" language="javascript">
            $(function() {
                $("#crateTable").click(function() {
                	var jsonVal = '{"tableComment": "测试数据sj","product": "globalhao123","data":'+ 
    														'[{"column": "ctime","type": "DATETIME","comment": "时间"},'+
    														'{"column": "name","type": "varchar","comment": "姓名"},'+
    														'{"column": "type","type": "bigint","comment": "类型"},'+
    														'{"column": "num","type": "decimal","comment": "数值"}]}';
                    $.ajax({
                    	  type : 'POST',
    										url : 'http://localhost:8080/api/etlservice/createTable',
    										dataType : 'json',
    										data : {json:jsonVal},
                        beforeSend: function(request) {
                        	//设置头信息
                            request.setRequestHeader("_product_line_", "HABO");
    						            request.setRequestHeader("_secret_key_", "123456");
    						            request.setRequestHeader("_username_", "heshenmi");
    						            request.setRequestHeader("_password_", "admin");
                        },
                        success: function(result) {
                            alert(result.code);
                        }
                    });
                });
            });
        </script>
    

      

    @Controller
    @RequestMapping("/api/etlservice")
    public class EtlController {
    	private static final Log log = LogFactory.getLog(EtlController.class);
    	@Autowired
    	private EtlService etl ;
    	@RequestMapping(value = "/createTable", method = RequestMethod.POST)
    	@ResponseBody
    	public ModelMap createTable(@RequestParam(value = "json", required = true) String json) {
    		log.info("createTable Json :"+json);
    		try {
    			etl.createTable(getEtlConfigByJson(json));
    		} catch (Exception ex) {
    			log.error("createTable failed:", ex);
    			return Results.failure("创建表失败:" + ex.getMessage());
    		}
    		log.info("createTable success");
    		return Results.success("创建表成功");
    	}
    

      request

    package demo;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.List;
    import java.util.Map;
    
    public class HttpRequest {
        /**
         * 向指定URL发送GET方法的请求
         * 
         * @param url
         *            发送请求的URL
         * @param param
         *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
         * @return URL 所代表远程资源的响应结果
         */
        public static String sendGet(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("_product_line_", "333");
                connection.setRequestProperty("_secret_key_", "3333");
                connection.setRequestProperty("_username_", "3333");
                connection.setRequestProperty("_password_", "3333");
                
                //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()));
                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;
        }
    
        /**
         * 向指定 URL 发送POST方法的请求
         * 
         * @param url
         *            发送请求的 URL
         * @param param
         *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
         * @return 所代表远程资源的响应结果
         */
        public static String sendPost(String url, String param) {
            PrintWriter out = null;
            BufferedReader in = null;
            String result = "";
            try {
                URL realUrl = new URL(url);
                // 打开和URL之间的连接
                URLConnection conn = realUrl.openConnection();
                // 设置通用的请求属性
                conn.setRequestProperty("_product_line_", "333");
                conn.setRequestProperty("_secret_key_", "3333");
                conn.setRequestProperty("_username_", "333");
                conn.setRequestProperty("_password_", "3333");
                
    //            conn.setRequestProperty("accept", "*/*");
    //            conn.setRequestProperty("connection", "Keep-Alive");
    //            conn.setRequestProperty("user-agent",
    //                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 发送POST请求必须设置如下两行
                conn.setDoOutput(true);
                conn.setDoInput(true);
                // 获取URLConnection对象对应的输出流
                out = new PrintWriter(conn.getOutputStream());
                // 发送请求参数
                out.print(param);
                // flush输出流的缓冲
                out.flush();
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                System.out.println("发送 POST 请求出现异常!"+e);
                e.printStackTrace();
            }
            //使用finally块来关闭输出流、输入流
            finally{
                try{
                    if(out!=null){
                        out.close();
                    }
                    if(in!=null){
                        in.close();
                    }
                }
                catch(IOException ex){
                    ex.printStackTrace();
                }
            }
            return result;
        }    
    }
    

      APITest

    package demo;
    
    import junit.framework.TestCase;
    
    
    public class APITest extends TestCase{
    	 public void createTable(){
    		//发送 GET 请求
    	    //String s=HttpRequest.sendGet("http://localhost:8080/api/demo/message", "json=product");
    	    //System.out.println(s);
    	    //发送 POST 请求
    		String createTableJson = "{"tableComment": "测试数据sj","product": "globalhao123","data": "+
    				"[{"column": "ctime","type": "DATETIME","comment": "时间"},"+
    				"{"column": "name","type": "varchar","comment": "姓名"},"+
    				"{"column": "type","type": "bigint","comment": "类型"},"+
    				"{"column": "num","type": "decimal","comment": "数值"}]}";
    	    String createTable=HttpRequest.sendPost("http://localhost:8080/api/etlservice/createTable", "json="+createTableJson);
    		System.out.println(createTable);
    	 }
    	public void insertData(){
    		String insertDataJson = "{"table": "globalhao123_crm_view_etl_1","ctimes": "2016-08-24 00:00:00,2016-08-25 00:00:00","
    				+ ""data": ["
    				+ "{"ctime": "2016-08-24 00:00:00","name": "黎明","type": "1","num": "2.11"},"
    				+ "{"ctime": "2016-08-25 00:00:00","name": "大熊","type": "4","num": "4"}]}";
    	    String insertData =HttpRequest.sendPost("http://localhost:8080/api/etlservice/insertData", "json="+insertDataJson);
    	    System.out.println(insertData);
    	}
    	public void deleteData(){
    		String deleteDataJson = "{"table": "globalhao123_crm_view_etl_1","ctimes": "2016-08-24 00:00:00,2016-08-25 00:00:00"}";
    	    String deleteData=HttpRequest.sendPost("http://localhost:8080/api/etlservice/deleteData", "json="+deleteDataJson);
    	    System.out.println(deleteData);
    	}
    }
    

      spring mvc.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
        <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
            <property name="alwaysUseFullPath" value="true" />
            <property name="interceptors">
                <list>
                    <bean class="com.baidu.sigma.api.AuthenticationInterceptor" />
                </list>
            </property>
        </bean>
        <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
            <property name="alwaysUseFullPath" value="true" />
            <property name="messageConverters">
                <list>
                    <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
                </list>
            </property>
        </bean>
        <context:component-scan base-package="com.baidu.sigma.api" />
    
    </beans>
    /**
     * 
     */
    package com.baidu.sigma.api;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    public class AuthenticationInterceptor implements HandlerInterceptor {
    
        private static final Log log = LogFactory.getLog(AuthenticationInterceptor.class);
    
        @Autowired
        private ProductLineService productLineService;
        @Autowired
        private LoginService  loginService;
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            String prod = RequestHelper.getProductLine(), key = RequestHelper.getSecretKey(),username=RequestHelper.getUserName(),password=RequestHelper.getPassword();
            boolean handled = false;
            if (prod == null || prod.isEmpty() || key == null || key.isEmpty()) {
                handled = true;
            } else {
                ProductLine product = productLineService.getProductLine(prod);
                if (product == null || !key.equals(product.getApiKey())) {
                    handled = true;
                }
            }
            //添加用户名验证
            if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
                handled = true;
            } else {
                Map <String ,String > userMap = new HashMap <String ,String> ();
                userMap.put("name",username);
                userMap.put("pwd", password);
                User user = loginService.validateUser(userMap);
                if(user == null ){
                    handled = true;
                }
            }
            if (handled) {
                log.warn("product line [" + prod + "] or " + "secret key [" + key + "] is illegal");
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(Results.message(Results.CODE_AUTHENTICATION_FAILED, "权限认证失败").toString());
                return false;
            }
            log.info(String.format("[%s] invoke api %s", prod, request.getRequestURI()));
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                ModelAndView modelAndView) throws Exception {
    
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
                throws Exception {
    
        }
    
    }

     http://www.iteye.com/topic/1143043

  • 相关阅读:
    利用多线程,执行有返回值的方法
    数组的Length属性用起来比把长度放在一个局部变量高效
    node.js + mongodb 做项目的详解(一)
    d3.js 之SVG:矢量化图形绘制
    d3.js 之增加感染力:使用转场效果
    d3.js 之关联数据:data操作符
    d3.js:数据可视化利器之 交互行为:响应DOM事件
    d3.js:数据可视化利器之 修改文档:DOM操作符
    d3.js:数据可视化利器之 selection:选择集
    d3.js:数据可视化利器之快速入门
  • 原文地址:https://www.cnblogs.com/sj521/p/6143878.html
Copyright © 2011-2022 走看看