Search code examples
c#asp.nethttpwebrequestwebclientrest-client

Simple http web post request not working properly from c# code, whereas same content from REST client is working fine


I have to request a URL i.e. "http://192.168.220.12:5000" where a java service will receive it,

with following string as Body

<?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>

I am able to do it successfully with RESTClient from my firefox browser, see the image below: enter image description here But when I send it through following C# code it gives me following error:

 java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(Unknown Source)
    at Creader.run(Creader.java:42)

C# code is as follows:

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));
}

What am I doing wrong here?

I also tried following but nothing worked. 1) Convert xmlData to byte [] using another method . 2) used Encoding.UTF8.GetBytes instead of Encoding.ASCII.GetBytes. 3) used client.UploadString(new Uri(mlcAddress), xmlData) instead of client.UploadData...


Solution

  • Following code (TCP socket) worked

    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);