C# 使用TcpClient获取字符串中的数据
我需要使用TcpClient将数据转换成字符串。该站点也需要身份验证。我发现了一个将数据导入流的片段,但它正在抛出 连接意外终止的异常 。下面是示例代码C# 使用TcpClient获取字符串中的数据,c#,asp.net,tcpclient,C#,Asp.net,Tcpclient,我需要使用TcpClient将数据转换成字符串。该站点也需要身份验证。我发现了一个将数据导入流的片段,但它正在抛出 连接意外终止的异常 。下面是示例代码 TcpClient oClient = new TcpClient(); oClient.Connect("xxx.xxx.xxx.xxx", 80); NetworkStream ns = oClient.GetStream(); StreamWriter sw = new StreamWriter(ns); sw.Write(
TcpClient oClient = new TcpClient();
oClient.Connect("xxx.xxx.xxx.xxx", 80);
NetworkStream ns = oClient.GetStream();
StreamWriter sw = new StreamWriter(ns);
sw.Write(
string.Format(
"GET /{0} HTTP/1.1\r\nUser-Agent: {1}\r\nHost: iq\r\n\r\n",
"/",
"MyTCPClient")
);
sw.Flush();
StringBuilder sb = new StringBuilder();
while (true)
{
int i = ns.ReadByte(); // Inefficient but more reliable
if (i == -1) break; // Other side has closed socket
sb.Append((char)i); // Accrue 'c' to save page data
}
oClient.Close();
如何也包括身份验证步骤
附言:总结一下,我想使用TcpClient获取一个字符串页面的html,它还涉及身份验证
编辑:我选择这种方法,因为URL末尾有一个句点,它被URI删除了。首先,为什么只有TcpClient?第二,什么时候会出现连接意外终止的异常?我认为您可以在TCP客户端中包含普通的NetworkCredential,但由于您没有指定需要使用哪种身份验证,因此很难回答这个问题……我在这里没有看到任何可以执行任何身份验证的内容。因此,可能是由于身份验证失败而关闭了连接。您应该使用HttpWebRequest,它提供HTTP感知功能,例如处理请求和响应头以及身份验证。