我想从F#调用外部POST API,该API具有如下所示的多部分表单请求主体,因此如何在F#中进行操作?
External POST API
url : “https://”
Content-Type : Multipart/Form-data
Body :- key(file) -> value(file which is browsed)
key(secured) -> value(String)
感谢您阅读此问题。
我尝试了以下代码,但对我不起作用
Http.Request
( "http://endpoint/for/multipart/data",
body = Multipart(
boundary = "define a custom boundary here", // this is used to separate the items you're streaming
parts = [
MultipartItem("formFieldName", "file",IFormFile.OpenReadStream())
]
))
答案 0 :(得分:0)
我将为此使用HTTp客户端,在fsharp中,您可以使用F# Data: HTTP Utilities之类的各种东西,或者我建议使用HTTP.fs的HTTP客户端软件包:
只需创建一个控制台应用程序并添加此nuget包
dotnet new console -lang f# -o http-rest-client
cd http-rest-client
dotnet add package Http.fs
dotnet add package Hopac
然后用以下代码替换Program.fs中的代码:
了解有关F#的更多信息open System.IO
open System.Text
open Hopac
open HttpFs.Client
let multipartRequest =
Request.createUrl Post "http://httpbin.org/post"
|> Request.setHeader (Accept "application/json")
|> Request.body (BodyForm [
FormFile ("file", ("testfile.txt",
ContentType.create("text", "plain"),
Binary (File.ReadAllBytes ("./testfile.txt"))
))])
|> Request.responseAsString
|> run
[<EntryPoint>]
let main argv =
printfn "%s" multipartRequest
0
创建一个文件,在这种情况下,可以更好地查看具有可读内容的.txt文件。和httpbin p用于测试目的,在我的情况下,该文件包含:
➜ cat testfile.txt
calimero calimero calimero calimero
然后您可以运行您的项目:
dotnet run
{
"args": {},
"data": "",
"files": {
"file": "calimero calimero calimero calimero\n"
},
"form": {},
"headers": {
"Accept": "application/json",
"Content-Length": "241",
"Content-Type": "multipart/form-data; boundary=\"BPj'o/kJ+CaKDQUuOnIaoLq/diChFH\"",
"Host": "httpbin.org"
},
"json": null,
"origin": "83.53.248.254, 83.53.248.254",
"url": "https://httpbin.org/post"
}
Http.fs包中有很多发送表单的示例,并且库设法添加了multipart-form-data
所需的herader。