[简约webAPI]分别以asp|jsp|php简单粗暴实现webAPI,输出json数据

2021-01-20 01:17

阅读:738

id="Label3" contentScore="1057">

标签:encode   UNC   hex   文件类型   port   返回   let   star   头部   

[简约webAPI]分别以asp|jsp|php简单粗暴实现webAPI,输出json数据

原本打算使用golang编写一个RESTful API,但因为环境所限,此次采用“偷懒的方式”,其实也不算偷懒,至少编写代码上面没有偷懒,只是在部署上偷懒了,三台机器物理地址以及公网地址均不同,说白了就是这三玩意儿没在一块,嘛都没在,好嘛,服务器环境也均然不同,分别为asp、java、php编写部署的系统。

既然都是脚本语言,那就暴力解决此次问题,灵活性毕竟很高嘛。

ASP+sqlServer

废话不多说上代码

"VBSCRIPT" CODEPAGE="65001"%>
‘utf8编码必须添加这个东东,还必须在第一行,不然无法生效 %>文件类型,json %>Response.ContentType = "application/json; charset=utf-8" %>html头部添加,如果编码使用utf8 %>   内置这个json库       VBS JSON 2.0.3    Copyright (c) 2009 Tu?rul Topuz    Under the MIT (MIT-LICENSE.txt) license.
Const JSON_OBJECT    = 0
Const JSON_ARRAY    = 1

Class jsCore
    Public Collection
    Public Count
    Public QuotedVars
    Public Kind  0 = object, 1 = array

    Private Sub Class_Initialize
        Set Collection = CreateObject("Scripting.Dictionary")
        QuotedVars = True
        Count = 0
    End Sub

    Private Sub Class_Terminate
        Set Collection = Nothing
    End Sub

     counter
    Private Property Get Counter 
        Counter = Count
        Count = Count + 1
    End Property

     - data maluplation
     -- pair
    Public Property Let Pair(p, v)
        If IsNull(p) Then p = Counter
        Collection(p) = v
    End Property

    Public Property Set Pair(p, v)
        If IsNull(p) Then p = Counter
        If TypeName(v)  "jsCore" Then
            Err.Raise &hD, "class: class", "Incompatible types: ‘" & TypeName(v) & ""
        End If
        Set Collection(p) = v
    End Property

    Public Default Property Get Pair(p)
        If IsNull(p) Then p = Count - 1
        If IsObject(Collection(p)) Then
            Set Pair = Collection(p)
        Else
            Pair = Collection(p)
        End If
    End Property
     -- pair
    Public Sub Clean
        Collection.RemoveAll
    End Sub

    Public Sub Remove(vProp)
        Collection.Remove vProp
    End Sub
     data maluplation

     encoding
    Function jsEncode(str)
        Dim charmap(127), haystack()
        charmap(8)  = "\b"
        charmap(9)  = "\t"
        charmap(10) = "\n"
        charmap(12) = "\f"
        charmap(13) = "\r"
        charmap(34) = "\"""
        charmap(47) = "\/"
        charmap(92) = "\\"

        Dim strlen : strlen = Len(str) - 1
        ReDim haystack(strlen)

        Dim i, charcode
        For i = 0 To strlen
            haystack(i) = Mid(str, i + 1, 1)

            charcode = AscW(haystack(i)) And 65535
            If charcode 127 Then
                If Not IsEmpty(charmap(charcode)) Then
                    haystack(i) = charmap(charcode)
                ElseIf charcode 32 Then
                    haystack(i) = "\u" & Right("000" & Hex(charcode), 4)
                End If
            Else
                haystack(i) = "\u" & Right("000" & Hex(charcode), 4)
            End If
        Next

        jsEncode = Join(haystack, "")
    End Function

     converting
    Public Function toJSON(vPair)
        Select Case VarType(vPair)
            Case 0     Empty
                toJSON = "null"
            Case 1     Null
                toJSON = "null"
            Case 7     Date
                 toJSON = "new Date(" & (vPair - CDate(25569)) * 86400000 & ")"     let in only utc time
                toJSON = """" & CStr(vPair) & """"
            Case 8     String
                toJSON = """" & jsEncode(vPair) & """"
            Case 9     Object
                Dim bFI,i 
                bFI = True
                If vPair.Kind Then toJSON = toJSON & "[" Else toJSON = toJSON & "{"
                For Each i In vPair.Collection
                    If bFI Then bFI = False Else toJSON = toJSON & ","

                    If vPair.Kind Then 
                        toJSON = toJSON & toJSON(vPair(i))
                    Else
                        If QuotedVars Then
                            toJSON = toJSON & """" & i & """:" & toJSON(vPair(i))
                        Else
                            toJSON = toJSON & i & ":" & toJSON(vPair(i))
                        End If
                    End If
                Next
                If vPair.Kind Then toJSON = toJSON & "]" Else toJSON = toJSON & "}"
            Case 11
                If vPair Then toJSON = "true" Else toJSON = "false"
            Case 12, 8192, 8204
                toJSON = RenderArray(vPair, 1, "")
            Case Else
                toJSON = Replace(vPair, ",", ".")
        End select
    End Function

    Function RenderArray(arr, depth, parent)
        Dim first : first = LBound(arr, depth)
        Dim last : last = UBound(arr, depth)

        Dim index, rendered
        Dim limiter : limiter = ","

        RenderArray = "["
        For index = first To last
            If index = last Then
                limiter = ""
            End If 

            On Error Resume Next
            rendered = RenderArray(arr, depth + 1, parent & index & "," )

            If Err = 9 Then
                On Error GoTo 0
                RenderArray = RenderArray & toJSON(Eval("arr(" & parent & index & ")")) & limiter
            Else
                RenderArray = RenderArray & rendered & "" & limiter
            End If
        Next
        RenderArray = RenderArray & "]"
    End Function

    Public Property Get jsString
        jsString = toJSON(Me)
    End Property

    Sub Flush
        If TypeName(Response)  "Empty" Then 
            Response.Write(jsString)
        ElseIf WScript  Empty Then 
            WScript.Echo(jsString)
        End If
    End Sub

    Public Function Clone
        Set Clone = ColClone(Me)
    End Function

    Private Function ColClone(core)
        Dim jsc, i
        Set jsc = new jsCore
        jsc.Kind = core.Kind
        For Each i In core.Collection
            If IsObject(core(i)) Then
                Set jsc(i) = ColClone(core(i))
            Else
                jsc(i) = core(i)
            End If
        Next
        Set ColClone = jsc
    End Function

End Class

Function jsObject
    Set jsObject = new jsCore
    jsObject.Kind = JSON_OBJECT
End Function

Function jsArray
    Set jsArray = new jsCore
    jsArray.Kind = JSON_ARRAY
End Function

Function toJSON(val)
    toJSON = (new jsCore).toJSON(val)
End Function
%>

‘浩秦版权所有root@landv.pw ASP数据库数据输出JSONhttp://www.dahuangphone.com/dispbbs.asp?boardid=8&Id=32&authorid=4开始查询并输出json
dim aa
aa = Request.QueryString("aa")
If aa"" Then
     true
     这是设置密码的地方
    if aa ="密码" Then
        QueryDate
    End if
Else
     false
     仅限调试使用
    Response.Write "aa为空"
    Response.End
End if

需要在外部进行声明
dim conn

Sub LinkDate()
     链接数据库
Dim ConnStr
ConnStr = "Provider = Sqloledb; User ID =用户名 ;Password=密码;Initial Catalog =数据库名字;Data Source =数据库地址;"
On Error Resume Next
Set conn = Server.CreateObject("ADODB.Connection")
conn.open ConnStr
If Err Then
     true
     仅限调试使用
    Set conn = Nothing
    Response.Write "no"
    Response.End
Else
     false
     仅限调试使用
    Response.Write "yes"
    Response.End
End if
End Sub
 貌似永远用不上关闭哈
Sub CloseDate()
     关闭链接
    If IsObject(conn) Then
         true
        conn.Close
        set conn=Nothing
    Else
         false
    End if
End Sub

Sub QueryDate()
     查询数据并返回
     ADO查询 https://www.runoob.com/ado/ado-query.html
     链接数据库
    LinkDate
     查询语句
     emmm从这里过滤字段即可,不用一个一个对应json了
    sql = "SELECT * FROM 数据库名字和判断"
     输出json
    Response.Write QueryToJSON(conn, sql).Flush
     关闭数据库
    CloseDate
End Sub
%>

‘QueryToJSON 此函数来自JSON官方JSON_UTIL_0.1.1.asp
Function QueryToJSON(dbc, sql)
        Dim rs, jsa
        Set rs = dbc.Execute(sql)
        Set jsa = jsArray()
        While Not (rs.EOF Or rs.BOF)
                Set jsa(Null) = jsObject()
                For Each col In rs.Fields
                        jsa(Null)(col.Name) = col.Value
                Next
        rs.MoveNext
        Wend
        Set QueryToJSON = jsa
End Function
%>

jsp+mysql

链接的mysql数据库,jsp需要下载两个jar包,gson和mysql

    pageEncoding="UTF-8"%>
import="java.io.*,java.util.*,java.sql.*"%>
import="javax.servlet.http.*,javax.servlet.*" %>

 --%>
//www.it610.com/article/5283384.htm --%>
import="com.google.gson.JsonArray"%>
import="com.google.gson.JsonObject"%>
import="java.sql.DriverManager"%>
import="java.sql.ResultSet"%>
import="java.sql.Statement"%>
import="java.sql.Connection"%>

//
//out.println("你的 IP 地址 " + request.getRemoteAddr());
String result = request.getParameter("aa");
//func转换成int类型,不如switch无法进行判断哈,奶奶个熊的,switch还不支持string,写这种古老技法还得研究一下,靠。
int func = Integer.parseInt(request.getParameter("func"));
String startData = request.getParameter("startData"); //开始时间
String stopData = request.getParameter("stopData"); //结束时间
String customSql =request.getParameter("customSql");//自定义SQL,需要过滤,只保留select函数indexOf,
String zz = "你的密码"; //密码验证
//out.println(result); 
//out.println(zz); 
//登录密码验证
if(zz.equals(result)){
    //功能判断
    switch(func) {
        case 0:
            //执行约定好的功能
            String strReturn;
            strReturn = queryHaccount();
            out.println(strReturn);
            //out.println("0");
            break;
        case 1:
            //功能二
            out.println("1");
            break;
        case 2:
            out.println("2");
            break;
        default:
            out.println("default");
    }
}
%>


String queryHaccount(){
    String strMessage = null;
    String sql ="SELECT * FROM 数据库名字和where过滤"; //先查询在完善
    //数据库链接
    Connection conn =null;
    //向数据库发送sql语句
    Statement st = null;
    //结果集
    ResultSet rs = null;
    // 数据库链接字符串
    String url = "jdbc:mysql://IP:3306/数据库名字?useUnicode=true&characterEncoding=utf-8";
    String user ="用户名";
    String pass ="密码";
    try{
        Class.forName("com.mysql.jdbc.Driver");
        //数据库的地址,密码,用户名
        conn =DriverManager.getConnection(url,user,pass);
        st = conn.createStatement();
        rs = st.executeQuery(sql);

        JsonObject object = new JsonObject();
        JsonArray array = new JsonArray();

        while(rs.next()){
            JsonObject ob = new JsonObject();
            //此处添加字段信息,先手动添加吧,后续写一个循环自动添加上。
            //这里得手动对应哈
            ob.addProperty("a",rs.getString("a"));
            ob.addProperty("b",rs.getString("b"));
            ob.addProperty("c",rs.getString("c"));

            array.add(ob);
        }
        object.add("landv",array);
        strMessage =object.toString();
        
    } catch (Exception e){

    }finally {
            try {
                rs.close();
            } catch (Exception e) {
            }
            try {
                st.close();
            } catch (Exception e) {
            }
            try {
                conn.close();
            } catch (Exception e) {
            }
    }
    return strMessage;    
}
%>

 

php+sqlServer

php不亏是php,几行就搞定了功能

php 
// https://www.cnblogs.com/zyf-zhaoyafei/p/4473924.html
// https://www.microsoft.com/en-us/download/details.aspx?id=20098
// 到微软官网下载SQL Server Driver for PHP
//https://www.jb51.net/article/56568.htm
//从jb51下载
//一般情况下是有的,在php\ext\php_pdo_mssql.dll
// 只需要在php-apache2handler.ini或者php.ini里面修改。
//去掉分号;extension=php_mssql.dll
//去掉分好;extension=php_pdo_mssql.dll
//实践出真理,还是使用jb51下载的这个52对应版本的吧
//https://blog.csdn.net/a1170201028/article/details/81191582
//通过PDO方式连接sqlserver
//https://www.jb51.net/article/135859.htm

//获取get信息
//密码验证
$aa = $_GET["aa"];
// 功能选择
$func = $_GET["func"];
$startData = $_GET["startData"]; //开始时间
$stopData = $_GET["stopData"]; //结束时间
$customSql = $_GET["customSql"]; //自定义SQL,需要过滤,只保留select函数
if ($aa=="你的密码") {
    # 登录验证
    # echo $aa;
    switch ($func) {
        case ‘0‘:
            # 执行约定好的功能
            FunctionQuery();
            #echo ‘10‘;
            break;
        case ‘1‘:
            # code...
            echo ‘1‘;
            break;        
        default:
            # code...
            echo "other";
            break;
    }
}

function FunctionQuery(){
    # code...
    $conn = new PDO("sqlsrv:server=数据库IP;database=数据库名字","用户名","密码");
    #条件语句
    $sql = "SELECT * FROM ";
    $res = $conn->query($sql);
    while ($row = $res->fetch()){
    #print_r($row);
    #https://www.cnblogs.com/yiven/p/6491019.html
    echo json_encode($row);//php好爽,比asp,jsp,json化数据好简单的说。哈哈哈哈
    }
}

?>

 

[简约webAPI]分别以asp|jsp|php简单粗暴实现webAPI,输出json数据

标签:encode   UNC   hex   文件类型   port   返回   let   star   头部   

原文地址:https://www.cnblogs.com/landv/p/12148026.html


评论


亲,登录后才可以留言!