我正在尝试使用以下代码向 LAN 上的 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
});
使用上面的代码效果很好(当然在浏览器中)
那么为了让它在 VB.net 中运行,我会缺少什么?
我也有类似的问题。我在浏览器客户端中使用 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 永远不会将数据返回到 jQuery AJAX 调用。