jquery VB.net 通过HttpWeb请求进行POST

d5vmydt9  于 2023-02-03  发布在  jQuery
关注(0)|答案(1)|浏览(122)

我尝试使用以下代码向局域网上的Arduino以太网微控制器发送命令:

Dim request As HttpWebRequest = HttpWebRequest.Create("http://192.178.47.19:19/?r=")
Dim POST As String = "r1"

request.Method = "POST"
request.ContentType = "text/html"
request.Headers.Add("Access-Control-Allow-Origin: *")
request.ContentLength = POST.Length
request.KeepAlive = True

Dim requestStream As Stream = request.GetRequestStream()
Dim postBytes As Byte() = Encoding.ASCII.GetBytes(POST)
requestStream.Write(postBytes, 0, postBytes.Length)
requestStream.Close()

然而,我得到的错误在线:

Dim requestStream As Stream = request.GetRequestStream()

说:

  • 基础连接已关闭:连接意外关闭。*

仅使用jQuery和 AJAX :

jQuery.support.cors = true;

  $.ajax({
        crossDomain: true,
        async : true,
        type: "POST",
        headers: {'Access-Control-Allow-Origin': '*'},
        url: "http://192.178.47.19:19/?r=" + whatsBeingSent,
        data: '{}',
        contentType: "text/html",
        dataType: "html",
        success: OnSuccessCallArduino,
        error: OnErrorCallArduino
  });

使用上面的代码就可以了(当然是在浏览器内部)
那么,为了让它在www.example.com中工作,我会错过什么VB.net?

eyh26e7m

eyh26e7m1#

我也有类似的问题。我在浏览器客户端使用jQuery AJAX 调用来访问一个aspx文件,该文件运行一个生成WebRequest响应的函数。这通常没有问题。但是,如果该函数使用WebRequest访问不同的服务器,响应是好的,但永远不会返回到原始AJAX调用,应用程序挂起。
浏览器 AJAX :

$.ajax({ dataType: "text", type: "POST", url: "WSProfile.aspx", async: false, data: { oper: 'FunctionSpecification', Data1: d1, Data2: d2 }, success: function (msg) { alert(msg); } });

WSProfile.Aspx:

Dim d1 As Text = Request.Form("Data1")
    Dim d2 As Text = Request.Form("Data2")

    Function getResponse(d1, d2)

    Dim request As WebRequest = WebRequest.Create("http://urlname.com")
    request.Method = "POST"
    Dim postData As String = "data1=" & d1 & "&data2=" & d2
    Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes(postData)
    request.ContentType = "application/x-www-form-urlencoded"
    request.ContentLength = byteArray.Length
    Dim dataStream As Stream = request.GetRequestStream()
    dataStream.Write(byteArray, 0, byteArray.Length)
    dataStream.Close()
    Dim response As WebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
    Dim Status As String = CType(response, HttpWebResponse).StatusDescription
        dataStream = response.GetResponseStream()
    Dim reader As New StreamReader(dataStream)

    Response.Write(reader.ReadToEnd())
    Response.Flush()

对另一个URL的调用会返回响应,但是对.aspx文件的原始调用的Response.Write不会将数据返回给 AJAX 调用。

相关问题