在 C# 中解析原始 HTTP 响应以获取状态代码
有没有一种简单的方法来解析 HTTP 响应字符串,如下所示:
"HTTP/1.1 200 OK\r\nContent-Length: 1433\r\nContent-Type: text/html\r\nContent-Location: http://server/iisstart.htm\r\nLast-Modified: Fri, 21 Feb 2003 23:48:30 GMT\r\nAccept-Ranges: bytes\r\nETag: \"09b60bc3dac21:1ca9\"\r\nServer: Microsoft-IIS/6.0\r\nX-Po"
我想获取状态代码。我不一定需要将其转换为 HttpResponse
对象,但这与解析状态代码一样是可以接受的。我可以将其解析为 HttpStatusCode
枚举吗?
我正在使用基于套接字的方法,无法改变我获得响应的方式。我只会使用这个字符串。
Is there a simple way to parse an HTTP Response string such as follows:
"HTTP/1.1 200 OK\r\nContent-Length: 1433\r\nContent-Type: text/html\r\nContent-Location: http://server/iisstart.htm\r\nLast-Modified: Fri, 21 Feb 2003 23:48:30 GMT\r\nAccept-Ranges: bytes\r\nETag: \"09b60bc3dac21:1ca9\"\r\nServer: Microsoft-IIS/6.0\r\nX-Po"
I would like to get the Status Code. I do not necessarily need to turn this in to an HttpResponse
object, but that would be acceptable as well as just parsing out the Status Code. Would I be able to parse that into the HttpStatusCode
enum?
I am using a sockets based approach and cannot change the way I am getting my response. I will only have this string to work with.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
编辑考虑到“我正在使用基于套接字的方法,并且无法更改我获取响应的方式。我只会使用这个字符串”。
怎么样:
我最初建议这个
EDIT Taking into account "I am using a sockets based approach and cannot change the way I am getting my response. I will only have this string to work with".
How about
I had originally suggested this:
HTTP 是一个非常简单的协议,以下应该可以非常可靠地获取状态代码(更新为更加健壮):
如果您确实想要,可以添加健全性检查以确保字符串以“HTTP”开头,但如果你想要稳健性,你也可以实现一个 HTTP 解析器。
说实话,这可能会做! :-)
HTTP is a pretty simple protocol, the following should get the status code out pretty reliably (updated to be a tad more robust):
If you really wanted to you could add a sanity check to make sure that the string starts with "HTTP", but then if you wanted robustness you could also just implement a HTTP parser.
To be honest this would probably do! :-)
如果它只是一个字符串,您不能只使用正则表达式来提取状态代码吗?
If it's just a string could you not just use a regex to extract the status code?
要么按照 DD59 建议执行,要么使用正则表达式。
Either do what DD59 suggests or use a regular expression.
这更新了标记的答案以处理一些极端情况:
This updates the marked answer to handle some corner cases:
因为状态代码的格式保持不变,你可能可以使用这样的东西。
coz the format of the status code remains same u can probably use smthing like this.