用C#实现HTTP协议,返回值总是Bad Request,大家帮忙看看
以下是代码:
IPAddress addr = null;
try
{
addr = IPAddress.Parse(this.tbIp.Text.Trim());
}
catch
{
addr = Dns.GetHostByName(this.tbIp.Text.Trim()).AddressList[0];
}
TcpClient tc = new TcpClient();
tc.Connect(new IPEndPoint(addr,Convert.ToInt32(this.tbPort.Text.Trim())));
NetworkStream nws = tc.GetStream();
StreamWriter sw = new StreamWriter(nws,System.Text.Encoding.UTF8);
sw.Write(strCommand);
sw.Flush();
string strRecived = "";
if(nws.CanRead)
{
MemoryStream ms = new MemoryStream();
byte[] bufferRecv = new byte[1024];
int nRecv = 0;
while(true)
{
if(nws.DataAvailable)
{
try
{
while(true)
{
nRecv = nws.Read(bufferRecv,0,bufferRecv.Length);
ms.Write(bufferRecv,0,nRecv);
if(nRecv == 0)
break;
}
}
catch(Exception err)
{
//读取错误
}
break;
}
}
ms.Seek(0,SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms,System.Text.Encoding.UTF8);
strRecived = sr.ReadToEnd();
sr.Close();
if(ms != null)
ms.Close();
nws.Close();
}
if(sw != null)
sw.Close();
if(tc != null)
tc.Close();
------------------
返回值总是Bad Request,这个代码哪里有问题吗?
IPAddress addr = null;
try
{
addr = IPAddress.Parse(this.tbIp.Text.Trim());
}
catch
{
addr = Dns.GetHostByName(this.tbIp.Text.Trim()).AddressList[0];
}
TcpClient tc = new TcpClient();
tc.Connect(new IPEndPoint(addr,Convert.ToInt32(this.tbPort.Text.Trim())));
NetworkStream nws = tc.GetStream();
StreamWriter sw = new StreamWriter(nws,System.Text.Encoding.UTF8);
sw.Write(strCommand);
sw.Flush();
string strRecived = "";
if(nws.CanRead)
{
MemoryStream ms = new MemoryStream();
byte[] bufferRecv = new byte[1024];
int nRecv = 0;
while(true)
{
if(nws.DataAvailable)
{
try
{
while(true)
{
nRecv = nws.Read(bufferRecv,0,bufferRecv.Length);
ms.Write(bufferRecv,0,nRecv);
if(nRecv == 0)
break;
}
}
catch(Exception err)
{
//读取错误
}
break;
}
}
ms.Seek(0,SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms,System.Text.Encoding.UTF8);
strRecived = sr.ReadToEnd();
sr.Close();
if(ms != null)
ms.Close();
nws.Close();
}
if(sw != null)
sw.Close();
if(tc != null)
tc.Close();
------------------
返回值总是Bad Request,这个代码哪里有问题吗?
...全文
相关推荐
C# WebApi 接口返回值不困惑:返回值类型详解
本文将深入解析C# WebApi中的返回值类型,针对初学者提供详尽的基础指南。首先,文章回顾了作者之前关于WebApi参数传递的分享,强调了返回值在API设计中的重要性。WebApi接口的返回值主要分
设备HTTP协议上传数据到OneNET接口规范.docx
2. 400 Bad Request:错误的请求格式。3. 401 Not Authorized:未经授权的访问。4. 403 Forbidden:禁止访问。
response和request(web开发技术第四章)
验证这些数据是否有效,如果无效,可以通过`response`设置状态码为400(Bad Request)并返回错误信息。3. 如果数据有效,可能执行数据库操作,如创建新用户。4.
http响应状态码
#### 4xx: 客户端错误状态码这一类状态码表示请求包含语法错误或请求无法实现。- **400 Bad Request**: 服务器不理解请求的语法。
C# WebApi 异常处理解决方案
在C# WebApi中,异常处理通常是指在客户端向WebApi发送HTTP请求时,服务端如何处理出现的异常情况,并将适当的错误信息以标准格式(如HTTP状态码)返回给客户端。


