首页 > 其他分享 >vb rest 接口 demo

vb rest 接口 demo

时间:2023-03-16 19:15:13浏览次数:47  
标签:Dim vb End String demo req System rest New

下面是帮一位 使用vb.net的朋友做的一个最简单 rest接口示例 ,详细源码见文章底部

最终效果如下:

默认查询 返回json

http://localhost:54370/Home/Index

clip_image002

clip_image004

 

 

默认创建表

http://localhost:54370/home/createtable

clip_image002[8]

clip_image004[10]

 

单记录插表

clip_image002[10]

测试调用代码

clip_image004[12]

clip_image006

多记录上传插表

clip_image008

测试调用代码

clip_image010

clip_image012

 

 vs2019  新建mvc工程

服务端代码 

Imports FreeSql
Imports Newtonsoft.Json

Public Class HomeController
    Inherits System.Web.Mvc.Controller

    Private Shared ykt As IFreeSql
    Shared Sub New()
        ykt = (New FreeSqlBuilder().UseAutoSyncStructure(True)).UseConnectionString(DataType.Sqlite, "Data Source=freedb.db", Nothing).Build()
    End Sub

    Public Function createtable() As String
        Return ykt.[Select](Of tech_info)().Any().ToString()
    End Function
    Public Function Index() As ActionResult
        Dim dict As IDictionary(Of String, Object) = New Dictionary(Of String, Object)() From
            {
                {"StateCode", 200}
            }
        Dim now As DateTime = DateTime.Now
        dict.Add("Message", String.Concat("接口访问成功,服务器时间", now.ToString()))
        Return MyBase.Json(dict, JsonRequestBehavior.AllowGet)
    End Function

    Public Function testUplaod(ByVal xx As List(Of ent_test)) As System.Web.Mvc.ActionResult
        Dim actionResult As System.Web.Mvc.ActionResult
        Dim retcode As Integer = -1
        Dim t2 As Integer = 0
        Dim key As String = DateTime.Now.ToString("yyyyMMddffff")
        tools.log(String.Concat(key, "接口被调用----------测试上传方法testuplaod------------------------------"))
        Dim sendstring As String = JsonConvert.SerializeObject(xx)
        'tools.log(String.Concat(key, "传入数据为:", sendstring))
        Try
            t2 = ykt.Insert(Of ent_test)(xx).ExecuteAffrows()
            tools.log(String.Concat(key, "数据插入行数-----", t2.ToString()))
            Return MyBase.Json(New With {Key .StateCode = 200, Key .Message = String.Concat("测试上传成功!行数:", t2.ToString(), "数据为:", sendstring)}, JsonRequestBehavior.AllowGet)
        Catch exception As System.Exception
            Dim ex As System.Exception = exception
            actionResult = MyBase.Json(New With {Key .StateCode = retcode, Key .Message = String.Concat(sendstring, ex.Message)}, JsonRequestBehavior.AllowGet)
        End Try
        Return actionResult
    End Function

    Public Function upload_tech_info(ByVal xx As tech_info) As System.Web.Mvc.ActionResult
        Dim actionResult As System.Web.Mvc.ActionResult
        Dim retcode As Integer = -1
        Dim t2 As Integer = 0
        Dim key As String = DateTime.Now.ToString("yyyyMMddffff")
        Dim sendstring As String = JsonConvert.SerializeObject(xx)
        tools.log(String.Concat(key, "接口被调用----------upload_tech_info-------", sendstring, "-----------------------"))
        Try
            t2 = ykt.Insert(Of tech_info)(xx).ExecuteAffrows()
            Return MyBase.Json(New With {Key .StateCode = 200, Key .Message = String.Concat("上传工艺信息成功!行数:", t2.ToString(), "数据为:", sendstring)}, JsonRequestBehavior.AllowGet)
        Catch exception As System.Exception
            Dim ex As System.Exception = exception
            actionResult = MyBase.Json(New With {Key .StateCode = retcode, Key .Message = String.Concat(sendstring, ex.Message)}, JsonRequestBehavior.AllowGet)
        End Try
        Return actionResult
    End Function
End Class

  测试客户端代码

Imports System.IO
Imports System.Net
Imports Newtonsoft.Json
Imports System.Text

Module Module1

    Sub Main()

        '印刷rest接口测试()

        工单状态上传()
    End Sub

    '多记录上传
    Private Sub 印刷rest接口测试()
        Dim postdata As List(Of ent_test) = New List(Of ent_test)() From
        {
            New ent_test() With
            {
                .usercode = "001",
                .username = "张三"
            },
            New ent_test() With
            {
                .usercode = "002",
                .username = "李四"
            },
            New ent_test() With
            {
                .usercode = "003",
                .username = "王五"
            }
        }
        Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://localhost:54370/home/testUplaod"), HttpWebRequest)
        req.Method = "POST"
        req.ContentType = "application/json"
        Dim sendstring As String = JsonConvert.SerializeObject(postdata)
        Dim data As Byte() = Encoding.UTF8.GetBytes(sendstring)
        req.ContentLength = CLng(CInt(data.Length))
        Using reqstream As Stream = req.GetRequestStream()
            reqstream.Write(data, 0, CInt(data.Length))
            reqstream.Close()
        End Using
        Dim response As HttpWebResponse = DirectCast(req.GetResponse(), HttpWebResponse)
        Dim text As String = String.Empty
        Using responseStm As Stream = response.GetResponseStream()
            text = (New StreamReader(responseStm, Encoding.UTF8)).ReadToEnd()
        End Using
        Console.WriteLine(text)
        Console.ReadKey()
    End Sub

    '单记录上传
    Private Sub 工单状态上传()
        Dim postdata As tech_info = New tech_info() With
        {
            .id = 3,
            .b = 4,
            .c = 5,
            .d = 6
        }
        Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://localhost:54370/home/upload_tech_info"), HttpWebRequest)
        req.Method = "POST"
        req.ContentType = "application/json"
        Dim sendstring As String = JsonConvert.SerializeObject(postdata)
        Dim data As Byte() = Encoding.UTF8.GetBytes(sendstring)
        req.ContentLength = CLng(CInt(data.Length))
        Using reqstream As Stream = req.GetRequestStream()
            reqstream.Write(data, 0, CInt(data.Length))
            reqstream.Close()
        End Using
        Dim response As HttpWebResponse = DirectCast(req.GetResponse(), HttpWebResponse)
        Dim text As String = String.Empty
        Using responseStm As Stream = response.GetResponseStream()
            text = (New StreamReader(responseStm, Encoding.UTF8)).ReadToEnd()
        End Using
        Console.WriteLine(text)
        Console.ReadKey()
    End Sub

End Module

  

标签:Dim,vb,End,String,demo,req,System,rest,New
From: https://www.cnblogs.com/hlm750908/p/17223813.html

相关文章

  • python并行计算demo,用于求0~n之间的素数之和
     想试试服务器的并行计算能力,就让cpu慢慢计算,计算0~n之间所有素数之和设置target为结尾,num_of_processors为进程数,即可开始跑如下所示frommultiprocessingimportP......
  • python 雪花算法demo
    importtimeimportloggingclassInvalidSystemClock(Exception):"""时钟回拨异常"""pass#64位ID的划分WORKER_ID_BITS=5DATACENTER_ID_B......
  • 单核无操作系统如何实现任务并行运行demo之ardiuno读取MPU6050进行oled显示和控制ws28
    实物演示​​视频请转向哔站​​1.起源一直想做一个多种模式显示的灯阵控制小玩意作为床头灯,这样每次一个人在乌漆嘛黑的卧室刷手机时能够给自己带来一丝暖意!!!此外在......
  • rabbitmq-demo
    demoConnectionFactory、Connection、Channel都是RabbitMQ对外提供的API中最基本的对象。Connection是RabbitMQ的socket链接,它封装了socket协议相关部分逻辑。ConnectionF......
  • vue + djangorestframework實現文件下載功能
    1.安裝模塊及配置及配置先安裝django-cors-headers包pip3installdjangorestframeworkdjango-cors-headers 在setting文件中註冊appINSTALLED_APPS=['djang......
  • nginx+lua+openresty+kafka相关问题汇总
    这里使用的是kafka插件是doujiang大佬的https://github.com/doujiang24/lua-resty-kafka,版本为v0.2.0。应用场景在nginx转发中,记录非200请求的信息,遂打算在log_by_lua*中......
  • ERROR 10516 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
    在IDEA上运行程序时遇到如下问题:如果你跟我一样也遇到了这个问题,那么大概率是端口冲突造成的。可能是之前运行的程序没有完全关闭从而影响到了现在的程序运行,最根本的解......
  • Quartz组件的搭建及实现任务调度demo
    1.基本环境配置<dependency>​<groupId>org.slf4j</groupId>​<artifactId>slf4j-log4j12</artifactId>​<version>1.7.25</version>​</dependency><d......
  • Ubuntu - Which services should be restarted?
    Ubuntu22.0当我使用apt安装一些软件包时,总是弹出一个粉色窗口,询问是否重启服务?原因是系统默认安装了needrestart,在每个apt安装完成后都会检查是否有更新,如果有......
  • springboot中RestTemplate的用法
    配置RestTemplate用于get请求携带multipart/form-data数据原生的RestTemplate在发送get请求时,无法携带body数据,但是有时候咱们的业务场景需要这样做,所以我们可以对RestTem......