gpt4 book ai didi

http - 从 WebResponse 响应流读取响应

转载 作者:塔克拉玛干 更新时间:2023-11-01 19:10:11 30 4
gpt4 key购买 nike

我一直在 F# 交互式 session 中尝试一些基本的 HTTP 请求响应操作,以尝试更好地感受这门语言。这里的一切似乎都按预期工作,除了当我获得 HTTP 请求的响应流时,我似乎永远无法从中读取任何内容。在下面的代码中,我每次都从 printfn 行获取文本,但是 responseString 的值似乎总是为空。我遗漏了什么明显的东西吗?

let httpListener = new HttpListener()
httpListener.Prefixes.Add("http://*:8020/")

let getContext = Async.FromBeginEnd(httpListener.BeginGetContext, httpListener.EndGetContext)

let processRequest = async {
while true do
let! context = getContext
let request = context.Request
use requestReader = new StreamReader(request.InputStream)
let requestString = requestReader.ReadToEnd()
let response = context.Response
use streamWriter = new StreamWriter(response.OutputStream)
streamWriter.WriteLine "A response!"
response.Close()
}

httpListener.Start()

let maxThreads = 10
for n = 0 to maxThreads do
Async.Start processRequest

printfn "HttpListener started with %d maximum threads processing requests." maxThreads

let sendRequest = async {
let request = WebRequest.Create("http://localhost:8020") :?> HttpWebRequest
let postBytes = Encoding.ASCII.GetBytes("Issuing HTTP")
request.Method <- "POST"
request.ContentType <- "application/x-www-form-urlencoded"
request.ContentLength <- int64 postBytes.Length
let requestStream = request.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
requestStream.Close()

let! response = Async.FromBeginEnd(request.BeginGetResponse, request.EndGetResponse)
let responseStream = response.GetResponseStream()
use streamReader = new StreamReader(responseStream)
let responseString = streamReader.ReadToEnd()

printfn "Received the following response: %s" responseString
}

for n = 0 to maxThreads do
Async.Start sendRequest

最佳答案

您需要减少 StreamWriter 的使用范围,以便它可以在 Dispose 上刷新。

let processRequest = async {
while true do
let! context = getContext
let request = context.Request
use requestReader = new StreamReader(request.InputStream)
let requestString = requestReader.ReadToEnd()
let response = context.Response
do
use streamWriter = new StreamWriter(response.OutputStream)
streamWriter.WriteLine "A response!"
response.Close()
}

关于http - 从 WebResponse 响应流读取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17961353/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com