[英]Post rest web api working from Postman but not returning any response from code in C# project
[英]Simple http web post request not working properly from c# code, whereas same content from REST client is working fine
我必须请求一个URL,即“ http://192.168.220.12:5000”,Java服务将在其中接收它,
以下字符串作为正文
<?xml version='1.0'?><!DOCTYPE svc_init SYSTEM 'ABCD.DTD'><svc_init ver='3.3.0'><hdr ver='3.3.0'><client><id>xxx</id><pwd>xxx</pwd></client></hdr><aaaa ver='3.3.0'><trans_id>1</trans_id><request_type type='2'/><l_hor_acc type='HIGH'/></aaaa></svc_init>
我可以通过Firefox浏览器使用RESTClient成功完成此操作,请参见下图: 但是,当我通过以下C#代码发送它时,出现以下错误:
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at Creader.run(Creader.java:42)
C#代码如下:
xmlData= "<?xml version='1.0'?><!DOCTYPE svc_init SYSTEM 'ABCD.DTD'><svc_init ver='3.3.0'><hdr ver='3.3.0'><client><id>xxx</id><pwd>xxx</pwd></client></hdr><aaaa ver='3.3.0'><trans_id>1</trans_id><request_type type='2'/><l_hor_acc type='HIGH'/></aaaa></svc_init>";
address = "http://192.168.220.12:5000";
using (var client = new WebClient())
{
client.UploadData(address , Encoding.ASCII.GetBytes(xmlData));
}
我在这里做错了什么?
我也尝试跟随,但没有任何效果。 1)使用另一种方法将xmlData转换为byte []。 2)使用Encoding.UTF8.GetBytes而不是Encoding.ASCII.GetBytes。 3)使用client.UploadString(new Uri(mlcAddress),xmlData)代替client.UploadData ...
WebRequest request = WebRequest.Create("http://192.168.220.12:5000");
request.Method = "POST";
string xmlData= "<?xml version='1.0'?><!DOCTYPE svc_init SYSTEM 'ABCD.DTD'><svc_init ver='3.3.0'><hdr ver='3.3.0'><client><id>xxx</id><pwd>xxx</pwd></client></hdr><aaaa ver='3.3.0'><trans_id>1</trans_id><request_type type='2'/><l_hor_acc type='HIGH'/></aaaa></svc_init>";
byte[] byteArray = Encoding.UTF8.GetBytes (xmlData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream ();
dataStream.Write (byteArray, 0, byteArray.Length);
dataStream.Close ();
WebResponse response = request.GetResponse ();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd ();
reader.Close ();
dataStream.Close ();
response.Close ();
以下代码(TCP套接字)有效
oSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
System.Net.IPAddress oIPAddress = System.Net.IPAddress.Parse(ip);
System.Net.IPEndPoint oEndPoint = new System.Net.IPEndPoint(oIPAddress, port);
oSocket.Connect(oEndPoint);
Object oData = xmlData;
byte[] bData = System.Text.Encoding.ASCII.GetBytes(oData.ToString());
oSocket.Send(bData);
您需要比较代码和REST客户端发送的内容之间的在线字节。 REST客户端有可能在一个数据包中发送标头和正文,而.NET则与正文分开发送请求标头,这导致服务器抛出异常,因为它不期望这样做。
使用wireshark嗅探流量,或者如果这是本地主机,则在firefox上使用Firebug,并为.net创建一个system.net跟踪日志。 只是谷歌为“与system.net跟踪”以获取有关如何执行此操作的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.