我想从 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())
]
))
最佳答案
我将为此使用 HTTP 客户端,在 fsharp 中你可以使用各种东西,例如 F# Data: HTTP Utilities或用于此目的的 HTTP 客户端包,我推荐 HTTP.fs :
只需创建一个控制台应用程序并添加此 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# 的更多信息,请访问 http://fsharp.org
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为了测试目的,在我的例子中,文件包含:
➜ 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
所需的 header
关于web - 如何从 F# 代码进行外部 POST API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56910353/