我一直在使用一个非常简单的Web服务器脚本,我对其进行了修改以充当代理。 但是,在创建发布请求(上传文件)时,似乎在更大的文件上失败。小文件(尝试使用一堆100kB文件)不是问题,但是大文件(6 mB)会失败,并且似乎会被截断。
如果我在Fiddler中检查了请求,我注意到身体的一部分正丢失。
似乎$request
未完成,或者从$request
到$data
的转换(带有函数提取)失败了。
我怀疑在读完数据后,我在将其写回时也会遇到问题,但是我怀疑解决方案是相同的。
代码:
function get-route($pattern) {
if ($pattern -like "*GET*") {
$page = (Invoke-WebRequest -Uri ($baseURL+$request.Url.LocalPath) -UseBasicParsing -WebSession $webSession ).Content
return $page
}
if ($pattern -like "*POST*") {
$data = extract $request
$page = (Invoke-WebRequest -Uri ($baseURL+$request.Url.LocalPath) -UseBasicParsing -Method Post -Body $data -ContentType $request.ContentType -WebSession $webSession -MaximumRedirection 10)
$page = $page.Content
return $page
}
}
# get post data from the input stream.
function extract($request) {
$length = $request.ContentLength64
$buffer = New-Object "Byte[]" $length
# option 1
[void]$request.InputStream.Read($buffer, 0, $length)
# # also tried this, but the result is the same
# # option 2
# $recvdBytes = 0
# $currOffset = 0
# $currLength = $length
# $currRead = 0
# while ($recvdBytes -lt $length) {
# $currRead = $request.InputStream.Read($buffer, $currOffset, $currLength)
# $recvdBytes += $currRead
# $currOffset += $currRead
# $currLength -= $curRead
# }
$body = [System.Text.Encoding]::GetEncoding("iso-8859-1").GetString($buffer)
return $body
}
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add($url)
$listener.Start()
while ($listener.IsListening) {
$context = $listener.GetContext()
$request = $context.Request
$response = $context.Response
$pattern = "{0} {1}" -f $request.HttpMethod, $request.Url.LocalPath
$route = get-route $pattern
$request.Url.OriginalString
#$route
if ($route -eq $null) {
$response.StatusCode = 404
} else {
$content = $route
$buffer = [System.Text.Encoding]::UTF8.GetBytes($content)
$response.ContentLength64 = $buffer.Length
$response.OutputStream.Write($buffer, 0, $buffer.Length)
}
$response.close()
}