我有一些通过CURL运行的命令,它们从API获得响应。我正在把它们转换成VB.net。
我有这个请求
curl --location --request GET http://ip:port/
,我像这样转换成vb.net。
Imports System
Imports System.IO
Imports System.Net
Module Module1
Sub Main()
' Make HTTP Request
Dim Request As HttpWebRequest = HttpWebRequest.Create("http://ip:port/")
Request.Method = "GET"
Request.Credentials = userCredentials
' Get HTTP Response
Dim response As HttpWebResponse = Request.GetResponse()
Dim reader As StreamReader = New StreamReader(Response.GetResponseStream())
Dim str As String = reader.ReadLine()
Do While str.Length >= 0
Console.WriteLine(str)
str = reader.ReadLine()
Loop
If (Console.ReadLine() = "EXIT") Then
Environment.Exit(0) 'or, simply return from the Main method
End If
End Sub
End Module
响应符合预期。
现在我有了另一个curl命令,它调用请求Post方法并将文件下载到D:。所以它有额外的参数
curl --location --request POST "http://ip:port/copy" --header "Content-Type: application/json" --data-raw "{"file":"//path/file.xlsx"}" >> D:file.xlsx
我已经尝试了这个,直到现在,但我失去了如何传递所有的参数,使其工作。
Dim Request As HttpWebRequest = WebRequest.Create("http://ip:port/copy")
Request.Method = "POST"
Request.ContentType = "application/json"
Request.Credentials = userCredentials
我如何传递——data-raw和D:file.xlsx,我应该使用什么来获得响应。
如有任何帮助,不胜感激。
谢谢你。
如果你不使用HttpWebRequest, HttpClient(可从。net Framework 4.5中获得)被认为是一个更好的库。
——location参数指示curl遵循http重定向(用3XX代码响应),HttpClient会自动执行。
——data-raw参数发送数据,就像从html表单(内容类型为application/x-www-form-urlencoded)的文件控件提交一样。
我读了上面的信息:https://curl.se/docs/manpage.html
使用HttpClient,发布文件很简单:
Dim client As New HttpClient()
Dim content As New ByteArrayContent(IO.File.ReadAllBytes("path_to_my_file"))
Dim response As HttpResponseMessage = Await client.PostAsync("<my url>", content)
response.EnsureSuccessStatusCode()
可能是因为data-raw参数的原因,您需要使用MultipartFormDataContent
来代替ByteArrayContent
。
Dim client As New HttpClient()
Dim b As Byte() = IO.File.ReadAllBytes("<path_to_my_file>")
Dim ms As New IO.MemoryStream(b, 0, b.Length)
ms.Write(b, 0, b.Length)
Dim content = New MultipartFormDataContent()
content.Add(New StreamContent(ms))
Dim response As HttpResponseMessage = Await client.PostAsync("<my url>", content)
我希望这些对你有帮助。